// JavaScript Document
Element.implement({
  show: function(type){
		type = ($defined(type) ? type : 'block');
		this.setStyle('display', type);
		return this;
	},
	hide: function(){
		this.setStyle('display', 'none');
		return this;
	},
	isEmpty: function(){
		switch (this.get('tag')){
			case 'input':
			  return (this.value == '');
		  break;
			case 'select':
			  return (this.selectedIndex == 0);
			break;
		}
		return null;
	},
	makeClickable: function(){
		var anchor = this.getElement('a');
		if (anchor){
			this.setStyle('cursor', 'pointer');
			this.addEvent('click', function(event){
			  if (document.id(event.target) != anchor) window.location = anchor.href;

			});
		}
	}
});

document.id = function(id){
	return $(id);
};

/*
---

script: Class.Refactor.js

description: Extends a class onto itself with new property, preserving any items attached to the class's namespace.

license: MIT-style license

authors:
- Aaron Newton

requires:
- core:1.2.4/Class
- /MooTools.More

provides: [Class.refactor]

...
*/

Class.refactor = function(original, refactors){

	$each(refactors, function(item, name){
		var origin = original.prototype[name];
		if (origin && (origin = origin._origin) && typeof item == 'function') original.implement(name, function(){
			var old = this.previous;
			this.previous = origin;
			var value = item.apply(this, arguments);
			this.previous = old;
			return value;
		}); else original.implement(name, item);
	});

	return original;

 };


/*
---

script: URI.js

description: Provides methods useful in managing the window location and uris.

license: MIT-style license

authors:
- Sebastian Markbåge
- Aaron Newton

requires:
- core:1.2.4/Selectors
- /String.QueryString

provides: URI

...
*/

var URI = new Class({

	Implements: Options,

	options: {
		/*base: false*/
	},

	regex: /^(?:(\w+):)?(?:\/\/(?:(?:([^:@\/]*):?([^:@\/]*))?@)?([^:\/?#]*)(?::(\d*))?)?(\.\.?$|(?:[^?#\/]*\/)*)([^?#]*)(?:\?([^#]*))?(?:#(.*))?/,
	parts: ['scheme', 'user', 'password', 'host', 'port', 'directory', 'file', 'query', 'fragment'],
	schemes: {http: 80, https: 443, ftp: 21, rtsp: 554, mms: 1755, file: 0},

	initialize: function(uri, options){
		this.setOptions(options);
		var base = this.options.base || URI.base;
		if(!uri) uri = base;
		
		if (uri && uri.parsed) this.parsed = $unlink(uri.parsed);
		else this.set('value', uri.href || uri.toString(), base ? new URI(base) : false);
	},

	parse: function(value, base){
		var bits = value.match(this.regex);
		if (!bits) return false;
		bits.shift();
		return this.merge(bits.associate(this.parts), base);
	},

	merge: function(bits, base){
		if ((!bits || !bits.scheme) && (!base || !base.scheme)) return false;
		if (base){
			this.parts.every(function(part){
				if (bits[part]) return false;
				bits[part] = base[part] || '';
				return true;
			});
		}
		bits.port = bits.port || this.schemes[bits.scheme.toLowerCase()];
		bits.directory = bits.directory ? this.parseDirectory(bits.directory, base ? base.directory : '') : '/';
		return bits;
	},

	parseDirectory: function(directory, baseDirectory) {
		directory = (directory.substr(0, 1) == '/' ? '' : (baseDirectory || '/')) + directory;
		if (!directory.test(URI.regs.directoryDot)) return directory;
		var result = [];
		directory.replace(URI.regs.endSlash, '').split('/').each(function(dir){
			if (dir == '..' && result.length > 0) result.pop();
			else if (dir != '.') result.push(dir);
		});
		return result.join('/') + '/';
	},

	combine: function(bits){
		return bits.value || bits.scheme + '://' +
			(bits.user ? bits.user + (bits.password ? ':' + bits.password : '') + '@' : '') +
			(bits.host || '') + (bits.port && bits.port != this.schemes[bits.scheme] ? ':' + bits.port : '') +
			(bits.directory || '/') + (bits.file || '') +
			(bits.query ? '?' + bits.query : '') +
			(bits.fragment ? '#' + bits.fragment : '');
	},

	set: function(part, value, base){
		if (part == 'value'){
			var scheme = value.match(URI.regs.scheme);
			if (scheme) scheme = scheme[1];
			if (scheme && !$defined(this.schemes[scheme.toLowerCase()])) this.parsed = { scheme: scheme, value: value };
			else this.parsed = this.parse(value, (base || this).parsed) || (scheme ? { scheme: scheme, value: value } : { value: value });
		} else if (part == 'data') {
			this.setData(value);
		} else {
			this.parsed[part] = value;
		}
		return this;
	},

	get: function(part, base){
		switch(part){
			case 'value': return this.combine(this.parsed, base ? base.parsed : false);
			case 'data' : return this.getData();
		}
		return this.parsed[part] || '';
	},

	go: function(){
		document.location.href = this.toString();
	},

	toURI: function(){
		return this;
	},

	getData: function(key, part){
		var qs = this.get(part || 'query');
		if (!$chk(qs)) return key ? null : {};
		var obj = qs.parseQueryString();
		return key ? obj[key] : obj;
	},

	setData: function(values, merge, part){
		if (typeof values == 'string'){
			data = this.getData();
			data[arguments[0]] = arguments[1];
			values = data;
		} else if (merge) {
			values = $merge(this.getData(), values);
		}
		return this.set(part || 'query', Hash.toQueryString(values));
	},

	clearData: function(part){
		return this.set(part || 'query', '');
	}

});

URI.prototype.toString = URI.prototype.valueOf = function(){
	return this.get('value');
 };

URI.regs = {
	endSlash: /\/$/,
	scheme: /^(\w+):/,
	directoryDot: /\.\/|\.$/
 };

URI.base = new URI(document.getElements('base[href]', true).getLast(), {base: document.location});

String.implement({

	toURI: function(options){
		return new URI(this, options);
	}

});

/*
---

script: URI.Relative.js

description: Extends the URI class to add methods for computing relative and absolute urls.

license: MIT-style license

authors:
- Sebastian MarkbÃ¥ge


requires:
- /Class.refactor
- /URI

provides: [URI.Relative]

...
*/

URI = Class.refactor(URI, {

	combine: function(bits, base){
		if (!base || bits.scheme != base.scheme || bits.host != base.host || bits.port != base.port)
			return this.previous.apply(this, arguments);
		var end = bits.file + (bits.query ? '?' + bits.query : '') + (bits.fragment ? '#' + bits.fragment : '');

		if (!base.directory) return (bits.directory || (bits.file ? '' : './')) + end;

		var baseDir = base.directory.split('/'),
			relDir = bits.directory.split('/'),
			path = '',
			offset;

		var i = 0;
		for(offset = 0; offset < baseDir.length && offset < relDir.length && baseDir[offset] == relDir[offset]; offset++);
		for(i = 0; i < baseDir.length - offset - 1; i++) path += '../';
		for(i = offset; i < relDir.length - 1; i++) path += relDir[i] + '/';

		return (path || (bits.file ? '' : './')) + end;
	},

	toAbsolute: function(base){
		base = new URI(base);
		if (base) base.set('directory', '').set('file', '');
		return this.toRelative(base);
	},

	toRelative: function(base){
		return this.get('value', new URI(base));
	}

});

var Overlay = {
	
	init: function(){
		this.overlay = $('overlay-wrapper');
		this.overlayBg = $('overlay-bg');
	},
	
	open: function(){
		if (Browser.Engine.trident && Browser.Engine.version < 5) $(document.body).addClass('ie6');
		this.overlay.show();
		this.overlayBg.setStyles({
		  'opacity': 0.5,
			'width': $(document.body).getSize().x,
			'height': Math.max($(document.body).getSize().y, $('page-wrapper').getSize().y)
		});
	}
 };

var InputValidator = new Class({

  Implements: [Options, Events],
	
  options: {
		required: false,
		tests: []
	},
	
  initialize: function(input, options){
		
		this.setOptions(options);
		this.input = $(input);
		this.tests = new Array(this.options.tests).flatten();
		this.errors = [];
		this.input.addEvent('blur', function(){
		  this.validate();
		}.bind(this));
		
		this.errorMark = null;
		
		// events
		this.addEvent('error', function(event){
		  this.placeErrors();
		});
		this.addEvent('success', function(){
		  this.removeErrors();
		});
		
		return this;
	},
	
	addTest: function(test, message){
		this.tests.include(test, message);
	},
	
	validate: function(){
		this.errors.empty();
		var value = this.input.value.trim();
		if (value == ''){
			if (this.options.required) this.errors.include('Toto pole je povinné.');
		} else {
			this.tests.each(function(test){
				value.test(test.regexp) ? this.errors.erase(test.message) : this.errors.include(test.message);
			}, this);
		}
		this.errors.length ? this.fireEvent('error') : this.fireEvent('success');
	},
	
	getError: function(){
		return this.errors;
	},
	
	placeErrors: function(){
	  var parent = this.input.getOffsetParent();
		var coords = this.input.getCoordinates(parent);
		var message = this.errors.join('<br />');
		if (this.errorMark) this.errorMark.destroy();
		this.errorMark = new Element('span',{
		  'class': 'error-mark',
			'styles': {
				'top': 4,
				'left': coords.left + coords.width + 2
			}
		}).adopt(new Element('span',{
		  'class': 'error-content',
			'html': message
		})).inject(this.input, 'after');
		this.input.addClass('error');
	},
	
	removeErrors: function(){
		this.input.removeClass('error');
		if (this.errorMark) this.errorMark.destroy();
	}
	
});

var SelectValidator = new Class({

  Implements: [Options, Events],
	
  options: {
		required: false
	},
	
  initialize: function(select, options){
		this.setOptions(options);
		this.element = $(select);
		this.errors = [];
		this.element.addEvent('blur', function(){
		  this.validate();
		}.bind(this));
		this.element.addEvent('change', function(){
		  this.validate();
		}.bind(this));
		
		this.errorMark = null;
		
		// events
		this.addEvent('error', function(event){
		  this.placeErrors();
		});
		this.addEvent('success', function(){
		  this.removeErrors();
		});
		
		return this;
	},
	
	validate: function(){
		this.errors.empty();
		if (this.element.selectedIndex == 0){
			if (this.options.required) this.errors.include('Vyberte jednu z nabízených položek.');
		}
		this.errors.length ? this.fireEvent('error') : this.fireEvent('success');
	},
	
	getError: function(){
		return this.errors;
	},
	
	placeErrors: function(){
	  var parent = this.element.getOffsetParent();
		var coords = this.element.getCoordinates(parent);
		var message = this.errors.join('<br />');
		if (this.errorMark) this.errorMark.destroy();
		this.errorMark = new Element('span',{
		  'class': 'error-mark',
			'styles': {
				'top': 4,
				'left': coords.left + coords.width + 2
			}
		}).adopt(new Element('span',{
		  'class': 'error-content',
			'html': message
		})).inject(this.element, 'after');
		this.element.addClass('error');
	},
	
	removeErrors: function(){
		this.element.removeClass('error');
		if (this.errorMark) this.errorMark.destroy();
	}
	
});

var RadioGroup = new Class({

  Implements: [Events, Options],
	
	options: function(){
		//onChange: $empty(radio, index),
		//onCheck: $empty(radio, index),
		//onUncheck: $empty(radio, index)
	},
	
	initialize: function(radioGroup, options){
		this.group = $$(radioGroup);
		
		this.setOptions(options);
		
		this.current = false;
	  
		this.group.each(function(radio, index){
			var span = radio.getParent('span');
			span.addClass('ready');
		  var label = radio.getParent('label');
			label.addEvent('click', function(event){
			  event.preventDefault();
				this.check(index);
			}.bind(this));
		}, this);
		
		this.check();
		
		return this;
		
	},
	
	check: function(radioIndex){
		this.group.each(function(radio, index){
			if ($defined(radioIndex)) radio.checked = (radioIndex == index);
			var parent = radio.getParent('span');
		  if (radio.checked){
				parent.addClass('checked');
				this.fireEvent('check', [radio, index]);
				this.fireEvent('change', [radio, index]);
			} else {
				if (parent.hasClass('checked')){
					parent.removeClass('checked');
					this.fireEvent('uncheck', [radio, index]);
				}
			}
		}, this);
	},
	
	getElements: function(){
		return this.group;
	}

});

var Bubble = new Class({
											 
	Implements: Options,
	
	options: {
		orientation: 'left',
		position: 'top'
	},

  initialize: function(element, options){
		
		this.element = document.id(element);
		
		this.setOptions(options);
		
		this.orientation = $pick(this.element.get('orientation'), this.options.orientation);
		this.position = $pick(this.element.get('position'), this.options.position);
		
		this.content = this.element.get('html');
		
		this.build();
		
	},
	
	build: function(){
		
		var bubble = new Element('div', {
			'class': 'bubble orientation-{orientation} position-{position}'.substitute({orientation: this.orientation, position: this.position}),
		  'html': '<div class="bubble-top-left"></div><div class="bubble-top-right"></div><div class="bubble-bottom-left"></div><div class="bubble-bottom-right"></div><div class="bubble-top"></div><div class="bubble-bottom"></div><div class="bubble-right"></div><div class="bubble-left"></div><div class="bubble-arrow"></div>'
		});
		
		var content = new Element('div', {
		  'class': 'bubble-content',
			'html': this.content
		});
		
		bubble.adopt(content);
		
		bubble.replaces(this.element);
		this.element = bubble;
		this.element.addEvent('click', function(event){
		  event.stopPropagation();
		});
	}

});

var Tabs = new Class({

  Implements: [Events, Options],
	
	options: {
		tabs: '.tab-anchors li',
		panels: '.tab-panel',
		disableClass: 'disabled',
		start: 0,
		observeDuration: 200,
		forceLinks: false
		//onShow: $empty(tab, panel, anchor),
		//onClose: $empty(tab, panel, anchor)
	},
	
	initialize: function(container, options){
		
		this.setOptions(options);
		
		this.container = document.id(container);
		this.tabs = new Hash(); // contains pairs of tabs and panels with anchor as id
		this.anchors = new Array(); // contains all available tab ids
		this.handlers = this.container.getElements(this.options.tabs);
		
		this.current = null;
		this.defaultTab = null;

    this.handlers.each(function(handler){
		   this.addTab(handler);
			 var link = handler.getElement('a');
			 if (handler.hasClass('disabled') && link){
				 link.addEvent('click', function(event){
				   event.preventDefault()
				 });
			 }
			 if (handler.hasClass('default')){
				 this.defaultTab = link.get('href').replace('#','');
			 }
		}, this);
		
		// init default tab
		if (!this.defaultTab) this.defaultTab = this.anchors[this.options.start];
		var hash = new URI().get('fragment');
    if (this.tabs.has(hash)) this.defaultTab = hash;
		if (this.defaultTab){
			this.show(this.defaultTab);
		}
		
		// force links
		if (this.options.forceLinks){
			var links = document.id(document.body).getElements('a[href^=#]');
			links.each(function(link){
				var anchor = link.get('href').replace('#','');
				if (anchor){
					link.addEvent('click', function(event){
					  event.preventDefault();
						this.show(anchor)
					}.bind(this));
				}
			}, this);
		} else {
			// run observer
			this.repeater = this.observe.periodical(this.options.observeDuration, this);
		}
		this.container.addClass('ready');
		this.fireEvent('ready', this);
		
		return this;
		
	},
	
	addTab: function(handler){
		var anchor = handler.getElement('a').get('href');
    if (anchor.test(/^#(.)+$/)){
			var panel =  this.container.getElement(anchor);
			if (panel){
				anchor = anchor.replace('#', '');
				this.tabs.set(anchor, {
				  tab: handler,
					panel: panel.removeProperty('id').hide(),  // remove id to prevent browser from jumping in page
					anchor: anchor
				});
				this.anchors.include(anchor);
			}
		}
	},
	
	show: function(id){
		if (id == '') id = this.defaultTab;
		if (this.tabs.has(id)){
			var tabPanel = this.tabs.get(id);
			if (this.current){
				this.current.tab.removeClass('active');
				this.current.panel.hide();
				this.fireEvent('close', [this.current.tab, this.current.panel, this.current.anchor]);
			}
			var tabPanel = this.tabs.get(id);
			tabPanel.tab.addClass('active');
			tabPanel.tab.getElement('a').blur();
			tabPanel.panel.show();
			this.current = tabPanel;
			
			if (this.options.forceLinks) window.location.hash = '#'+id;
			this.fireEvent('show', [tabPanel.tab, tabPanel.panel, id]);
			
			this.fireEvent('change', this.tabs);
		}
	},
	
	observe: function(){
		var hash = window.location.hash.replace('#', '');
		if (hash != this.current.anchor){
      this.show(hash);
		}
	}
		
});

var Overlay = {
	
	init: function(){
		this.overlay = $('overlay-wrapper');
		this.overlayBg = $('overlay-bg');
	},
	
	open: function(){
		if (Browser.Engine.trident && Browser.Engine.version < 5) $(document.body).addClass('ie6');
		this.overlay.show();
		this.overlayBg.setStyles({
		  'opacity': 0.5,
			'width': $(document.body).getSize().x,
			'height': Math.max($(document.body).getSize().y, $('page-wrapper').getSize().y)
		});
	}
 };
 
 

var BackgroundSlideshow = new Class({
	
	Implements: [Events, Options],

  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){
		this.container = document.id(container);
		
		this.setOptions(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.Tween(this.slides[0], { property: 'opacity', duration: this.options.fxDuration, link: 'cancel' }).set(0);
		this.count = 1;
		this.timer = null;
		
		
		this.images = new Asset.images(this.paths, {
		  onComplete: function(){
				this.fireEvent('build');
			}.bind(this)
		});
		
		// class events
		this.addEvents({
		  'build': function(){ this.createSlides(); },
			'start': function(){ this.start(); }
		});
		
	},
	
	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.Tween(this.slides[index+1], { property: 'opacity', duration: this.options.fxDuration, link: 'cancel' }).set(0));
			this.slides[index+1].inject(this.container);
		}, this);
		
		this.count = this.slides.length;
		
		this.fireEvent('ready');
		if (this.options.auto) this.fireEvent('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);
	}
	
});

var Ceresit = {
	
	init: function(){
		
		Ceresit.Dealers.init();
		if ($('mapa-cr-wrapper')) Ceresit.Map.init();
		if ($('google-map')) Ceresit.GoogleMap.init();
		
		$$('.clickable').each(function(element){
		  new Ceresit.UI.Clickable(element);
		});
		
		$$('.print').each(function(element){
		  new Ceresit.UI.Print(element);
		});
		
		this.backgrounds = ['bg-1.jpg', 'bg-2.jpg', 'bg-3.jpg', 'bg-4.jpg'];
		// 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
		});
	}
	
 };

Ceresit.UI = {};

Ceresit.UI.Clickable = new Class({
  
	initialize: function(container){
		this.container = $(container);
		
		this.link = this.container.getElement('a');
		
		if (this.link){
			this.container.setStyle('cursor', 'pointer');
			this.container.addEvent('click', function(){
			  window.location = this.link.get('href');
			}.bind(this));
		}
	}

});

Ceresit.UI.Print = new Class({

  initialize: function(element){
		this.container = $(element);
		if (this.container){
			this.container.addEvent('click', function(event){
			  event.preventDefault();
			  window.print();
			});
		}
	}
});

Ceresit.Dealers = {
	
	init: function(){
		
		this.searchDealerInput = $('form-search-dealer-city');
		if (this.searchDealerInput) new Autocompleter.Request.JSON(this.searchDealerInput, '/prodejci/mesta');
		
		$$('.google-map').each(function(googleMap){
		  new Ceresit.Dealers.GoogleMap(googleMap);
		});
		
		// Forms
		Ceresit.Dealers.Form.init();
		
		// Shop detail
		if ($('shop-detail')){
			Ceresit.Dealers.Detail.init();
		}
		
		// Bubbles
		$$('div.bubble').each(function(element){
		  new Bubble(element);
		});
		
		var googleMapLoaded = false;
		
		$$('div.tabs').each(function(element){
		  new Tabs(element, {
			  forceLinks: true,
				onShow: function(tab, panel, anchor){
					if (anchor == 'mapa' && !googleMapLoaded){
						loadGoogleMap();
						googleMapLoaded = true;
					}
				}
			});
		});
		
		Ceresit.Dealers.List.init();
		
	}
 };

Ceresit.Dealers.GoogleMap = new Class({
	
	Implements: [Options, Events],
	
	options: {
		onZoomIn: $empty(),
		onZoomOut: $empty(),
		onStart: $empty(),
		toggle: '.google-map-toggle',
		canvas: '.google-map-canvas',
		toggleText: {
			zoomIn: 'Zobrazit větší mapu',
			zoomOut: 'Zobrazit menší mapu'
		}
	},
	
	initialize: function(container, options){
		
		this.container = $(container);
		this.setOptions(options);
		this.mapCanvas = this.container.getElement(this.options.canvas);
		this.toggle = this.container.getElement(this.options.toggle);
		
		if (this.toggle){
			this.toggleText = this.toggle.getElement('span');
			this.toggle.addEvent('click', function(event){
				if (this.isSmall()){
					this.container.addClass('big');
					this.toggleText.set('html', this.options.toggleText.zoomOut);
					this.container.fireEvent('zoomin');
					this.fireEvent('zoomin');
				} else {
					this.container.removeClass('big');
					this.toggleText.set('html', this.options.toggleText.zoomIn);
					this.container.fireEvent('zoomout');
					this.fireEvent('zoomout');
				}
			}.bind(this));
		}
		
	},
	
	isBig: function(){
		return this.container.hasClass('big');
	},
	
	isSmall: function(){
		return !this.container.hasClass('big');
	}
});

Ceresit.Map = {

	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.get('href').test('prodejci')){
					prefix = '/prodejci/';
				}
				if (element.get('href').test('soutez')){
					prefix = '/soutez/fotografie/';
				}
				var kraj = element.get('href').replace(prefix, '').replace('-kraj', '');
							 // bubble
				var bubble = new Element('p', { 'class' : 'bubble' });
				bubble.set('html', '<span>' + element.getProperty('title') +'</span>');
				bubble.setStyles({
						'left' : bubbles.get(kraj)[0],
						'top'  : bubbles.get(kraj)[1]
				});
				var bubbleFx = new Fx.Tween(bubble, { property: 'opacity', duration: 200, link: 'cancel' });
				bubbleFx.set(0);
				bubble.inject(field);
				
				element.addEvent('mouseenter', function(event){
						this.move(kraje.get(kraj), field);
						bubbleFx.start(1);
				}.bind(this));
				
				element.addEvent('mouseleave', function(event){
						this.move([0, 0], field); 
						bubbleFx.start(0);
				}.bind(this));
		 }, this);
		
	},
	
	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');
	}
		
 };
 
Ceresit.Dealers.Form = {
	
	init: function(){
		if ($('form-shop')) Ceresit.Dealers.Form.Shop.init();
		if ($('form-dealer-sort')) Ceresit.Dealers.Form.DealerSort.init();
		if ($('form-dealer-filter')) Ceresit.Dealers.Form.DealerFilter.init();
	}
 };

Ceresit.Dealers.Form.Shop = {
	
	options: {
		fieldNames: ['title', 'street', 'num', 'city', 'zip'],
		fieldsetNames: ['group-map', 'group-time'],
		prefix: 'form-shop-',
		validators: {
			'title' : { required: true, tests: { regexp: /.{3}/, message: 'Je nutné zadat alespoň tři znaky.' } },
			'street':  { required: true, tests: { regexp: /.{3}/, message: 'Je nutné zadat alespoň tři znaky.' } },
			'num':  { required: true },
			'city': { required: true, tests: { regexp: /.{2}/, message: 'Je nutné zadat alespoň dva znaky.' } },
			'zip': { required: true, tests: { regexp: /^\d{3} \d{2}$|^\d{5}$/, message: 'Neplatné PSČ. Příklad: <strong>123 45</strong>.' } },
			'province': { required: true },
			'email': { required: true, tests: { regexp: /[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}/, message: 'Zadaná emailová adresa je neplatná.' } },
			'web': { tests: { regexp: /(http\:\/\/)?([a-zA-Z0-9\.\-]+(\:[a-zA-Z0-9\.&%\$\-]+)*@)?((25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])|([a-zA-Z0-9\-]+\.)*[a-zA-Z0-9\-]+\.[a-zA-Z]{2,4})(\:[0-9]+)?(\/[^\/][a-zA-Z0-9\.\,\?\'\\\/\+&%\$#\=~_\-@]*)*/, message: 'Zadaná adresa je neplatná.' } },
			'chief': { tests: { regexp: /.{3}/, message: 'Zadejte alespoň tři znaky' } }
		}
	},
	
	init: function(){
		
		this.form = $('form-shop');
		
		this.uploader = $('swf-uploader');
		this.progress = this.uploader.getElement('.column2');
		this.progressFx = new Fx.Tween(this.progress, { property: 'opacity', duration: 300 }).set(0);
		
		// fields
		this.field = new Hash();
		this.fieldNames = this.options.fieldNames;
		
		this.fieldNames.each(function(fieldName){
			var field = $(this.getID(fieldName));
			field.addEvent('blur', function(){
			  this.checkAddress();
			}.bind(this));
		  this.field.set(fieldName, field);
		}, this);
		
		// fieldsets
		this.fieldsets = new Hash();
		this.fieldsetNames = this.options.fieldsetNames;
		
		this.fieldsetNames.each(function(fieldsetName){
		  this.fieldsets.set(fieldsetName, $(this.getID(fieldsetName)));
		}, this);
		
		this.fieldsets.get('group-map').hide();
		
		// error box
		this.errorBox = new Element('div', {
		  'id' : 'error-box',
			'html': '<p>Ve formuláři byly nalezeny chyby. Více informací získáte najetím myši na symbol <img src="/img/exclamation.png" width="14" height="14" alt="Vykřičník" /> u odpovídajícího pole.</p>'
		}).hide().inject('form-shop-group-title', 'before');
		
		// validators
		this.validators = new Hash();
		this.validatorConfigs = new Hash(this.options.validators);
		this.validatorConfigs.each(function(config, key){
		  var id = this.getID(key);
			var type = $(id).get('tag');
			switch (type){
				case 'input': 
				  this.validators.set(key, new InputValidator(id, config));
			  break;
				case 'select':
				  this.validators.set(key, new SelectValidator(id, config));
				break;
			}
		}, this);
		
		// Opening hours
		this.openingHours = [];
		this.fieldsets.get('group-time').getElements('p').each(function(item, index){
		  this.openingHours[index] = new Ceresit.Dealers.Form.Shop.OpeningHours(item, {
			  onChange: this.checkOpeningHours.bind(this)
			});
		}, this);
		
		this.checkOpeningHours();
		
		// validate on submit
		this.form.addEvent('submit', function(event){
		  event.stop();
			if (this.isValid()){
				if (confirm('Opravdu si přejete odeslat upravené údaje?')){
					this.openingHours.each(function(item){
						item.check();
					});
					Overlay.open();
					if ($('swf-uploader-list').getElements('li').length == 0){
						this.form.submit();
					} else {
						this.swiffy.upload();
					}
				}
			} else {
				this.displayErrorMessage();
			}
		
		}.bind(this));
		
		
		this.checkAddress();
		
		
		/* FLASH UPLOADER */
		this.browseBtn = $('swf-uploader-browse');
		this.clearBtn = $('swf-uploader-clear').hide();
		
		// prepare uploader
		this.createUploader();

    // browse button
    this.browseBtn.addEvent('click', function() {
			this.swiffy.browse();
			return false;
		}.bind(this));
	 
	  // delete all button
		this.clearBtn.addEvent('click', function() {
			this.swiffy.removeFile();
			return false;
		}.bind(this));
		
		
		// Overlay
		Overlay.init();
		
	},
	
	getID: function(name){
		return this.options.prefix + name;
	},
	
	checkAddress: function(){
		var mapFieldset = this.fieldsets.get('group-map');
		if (this.field.street.value.trim() != ''
		 && this.field.num.value.trim() != ''
		 && this.field.city.value.trim() != ''){
			mapFieldset.show();
			var str = this.field.street.value.trim() + ' ' + this.field.num.value.trim() + ', ' + this.field.city.value.trim();
			mapFieldset.getElement('a.map').set({
			  'href': 'http://www.mapy.cz/?query=' + str,
				'target': '_blank'
			});
		} else {
  		mapFieldset.hide();
		}
	},
	
	isValid: function(){
		var items = this.validators;
		var errors = 0;
		items.each(function(item){
			item.validate();
			errors += item.getError().length;
		});
		return !errors;
	},
	
	displayErrorMessage: function(){
		this.errorBox.show();
	},
	
	createUploader: function(){
		var uploadUrl = this.form.action + "?PHPSESSID=" + Cookie.read("PHPSESSID");
    this.swiffy = new FancyUpload2($('overlay'), $('swf-uploader-list'), {
			url: uploadUrl,
			fieldName: 'img',
			path: '/flash/Swiff.Uploader.swf',
			limitSize: 4 * 1024 * 1024, // 4Mb
			limitFiles: 10,
			onLoad: function() {
				$('swf-uploader').removeClass('hide');
				if ($('form-shop-photo-wrapper')) $('form-shop-photo-wrapper').destroy();
			},
			onBeforeOpen: function(){
				this.progressFx.start(1);
			}.bind(this),
			onAllSelect: function(){
				if (this.uploader.getElements('li').length) this.clearBtn.show('inline');
			}.bind(this),
			onAllComplete: function(){
				this.clearBtn.hide();
				this.form.submit();
			}.bind(this),
			typeFilter: {'Images (*.jpg, *.jpeg, *.gif, *.png)': '*.jpg; *.jpeg; *.gif; *.png'},
			debug: false, // enable logs, uses console.log
			target: 'swf-uploader-browse' // the element for the overlay (Flash 10 only)
		});
	},
	
	checkOpeningHours: function(){
		var isEmpty = true;
		this.openingHours.each(function(openingHour){
			if (!openingHour.isEmpty()) isEmpty = false;
		});
		if (isEmpty){
			this.openingHours.each(function(openingHour){
				openingHour.setDefaultText()
			});
		} else {
			this.openingHours.each(function(openingHour){
			  if (!openingHour.isChecked()) openingHour.setDisabledText();
			});
		}
	}
	
 };

Ceresit.Dealers.Form.Shop.OpeningHours = new Class({

  Implements: [Events, Options],
	
	options: {
		checkboxSelector: 'input[type=checkbox]',
		inputSelector: 'input[type=text]',
		disabledText: 'Zavřeno',
		defaultText: 'Neuvedeno'
	},
	
	initialize: function(container, options){
		this.container = $(container);
		this.setOptions(options);
		
		this.loaded = false;
		
		this.checkbox = this.container.getElement(this.options.checkboxSelector);
		this.input = this.container.getElement(this.options.inputSelector);
		
		// checkbox event
		this.checkbox.addEvent('change', this.checkStatus.bind(this));
		
		// IE onchange fix
		if (Browser.Engine.trident){
			this.checkbox.addEvent('click', this.checkbox.blur);
		}
		
		this.checkStatus();
		
		this.loaded = true;
	},
	
	disable: function(){
		this.input.disabled = true;
		this.input.value = this.options.disabledText;
	},
	
	enable: function(){
		this.input.disabled = false;
		this.input.value = this.input.defaultValue;
	},
	
	checkStatus: function(){
		this.checkbox.checked ? this.enable() : this.disable();
		if (this.loaded) this.fireEvent('change');
	},
	
	check: function(){
		if (!this.checkbox.checked) this.input.value = '';
	},
	
	isEmpty: function(){
		return !this.checkbox.checked && (this.input.value == this.options.disabledText || this.input.value == this.options.defaultText);
	},
	
	isChecked: function(){
		return this.checkbox.checked;
	},
	
	setDefaultText: function(){
		this.input.value = this.options.defaultText;
	},
	
	setDisabledText: function(){
		this.input.value = this.options.disabledText;
	}

});

Ceresit.Dealers.Form.DealerSort = {
	
	init: function(form){
	  this.form = document.id('form-dealer-sort');
		
		this.radios = this.form.getElements('input[type=radio]');
		
		this.labels = this.form.getElements('label');
		
		new RadioGroup(this.radios, {
		  onChange: function(radio, index){
				this.form.submit();
			}.bind(this)
		})
		
		this.radios.each(function(radio){
		  if (radio.checked) radio.getParent('label').addClass('selected');
		});
	}
	
 };
 
Ceresit.Dealers.Form.DealerFilter = {
	
	init: function(form){
	  this.form = document.id('form-dealer-filter');
		
		this.selects = this.form.getElements('select');
		
		this.selects.addEvent('change', function(event){
		  this.form.submit();
		}.bind(this));

	}
	
 };
 
Ceresit.Dealers.List = {
	
	init: function(){
		
		this.items = $$('ul.options li');
		
		if (this.items.length == 0) return;
		
		var body = document.id(document.body);
		
		var pageWrapper = document.id('page-wrapper');
		
		this.items.each(function(item){
		  var bubble = item.getElement('div.bubble');
			var bubbleLoaded = false;
			item.addEvents({
			  'mouseenter': function(){
					if (!bubbleLoaded){
						bubble.inject(pageWrapper);
						var position = item.getPosition(pageWrapper);
						var size = item.getSize();
						bubble.setStyles({
						  left: position.x,
							top: position.y
						});
						bubble.show('block');
						var bubbleSize = bubble.getSize();
						bubble.setStyle('left', position.x-bubbleSize.x+2);
						bubbleLoaded = true;
					} else {
						bubble.show('block');
					}
				},
				'mouseleave': function(){
					bubble.hide();
				}
			});
		});
		
	}
};

Ceresit.Dealers.Detail = {
	
	init: function(){
		
		this.container = $('shop-detail');
		this.images = this.container.getElements('.panel-gallery a');
		
		this.images.each(function(image){
			new ReMooz(image,{
				'shadow': 'onOpen',
				'resizeFactor': 0.9,
				'cutOut': false,
				'opacityResize': 0,
				'centered': true,
				'origin' : image.getElement('img')
			});
		});
		
		$$('ul.product-line li').makeClickable();
	}
 };
 

window.addEvent('domready', function(){

  Ceresit.init();

});

