/* SKINBOOK JavaScript library */
var Skinbook = {
	init: function(){
		Skinbook.swap();
		Skinbook.external();
		Skinbook.style();
		Skinbook.autoscroolto();
		Skinbook.over();
		
  		// Zapneme Growl
  		Growl.Bezel = new Gr0wl.Bezel('http://www.skinbook.cz/images/bezel.png');
		Growl.Smoke = new Gr0wl.Smoke('http://www.skinbook.cz/images/smoke.png');
  		Skinbook.autogrowl();
	},
	
	/* Náhrada a objevení textu v inputu */
	swap: function(){
		var swapvalues = [];
		$$('input.swapable').each(function(el){
			swapvalues[el.id] = $(el).value;
			el.addEvents({
				'focus' : function(){ this.value = "" },
				'blur' : function(){ this.value = swapvalues[this.id] }
			});
		});
	},

	/* Změní atribut odkazu na otevření v novém okně, validně pro XHTML Strict */
	external: function(){
		if (!document.getElementsByTagName) return;
		$$('a[rel=external]', 'a.external').each(function(el){
			if (el.href)
			{
				el.target = "_blank";
			}
		});
	},
	
	/* Přepínání stylů */
	style: function(){
		var style_text, style_graphic, incookie = Cookie.get("skinbook_style");
		if (incookie == "text")
		{
			// Grafický styl je automaticky načtený, pokud máme textový, musíme ho smazat
			$('style_graphic').remove();
			new Asset.css('http://www.skinbook.cz/css/skinbook_txt.css', {id: 'style_text'});
			current_style = $('style_text');
		}
		else
		{
			current_style = $('style_graphic');
		}
		
		
		$('style_text_trigger').addEvent('click', function(e) {
			e = new Event(e).stop();
			
			current_style.remove();
			Cookie.set("skinbook_style", "text");
			new Asset.css('http://www.skinbook.cz/css/skinbook_txt.css', {id: 'style_text'});
			current_style = $('style_text');
		});
		$('style_graphic_trigger').addEvent('click', function(e) {
			e = new Event(e).stop();
			
			current_style.remove();
			Cookie.set("skinbook_style", "graphic");
			new Asset.css('http://www.skinbook.cz/css/skinbook_czech.css', {id: 'style_graphic'});
			current_style = $('style_graphic');
		});
	},
	
	/* Automatické plynulé skrolování */
	autoscroolto: function(){
		$('usability_content').addEvent('click', function(e) {
			e = new Event(e).stop();
			new Fx.Scroll(window).toElement('content');
		});
		$('usability_menu').addEvent('click', function(e) {
			e = new Event(e).stop();
			new Fx.Scroll(window).toElement('menu');
		});
	},
    
    /* Měnění tlačítek */
    over: function(){
    	var original, subsitute;
    	$$('img[class=over]').each(function(el){
			el.addEvents({
				'mouseover': function(){
					original = el.src;
					el.src = el.getProperty('rel');
				},
				'mouseout': function(){
					el.src = original;
				}
			});
		});
    },
    
    /* Spustí všechny growly */
    autogrowl: function(){
    	var texts = new Array;
    	texts['newsletter'] = ['Novinky e-mailem', 'O všech novinkách na internetovém obchodě Skinbook budete informování hezky začerstva e-mailem.'];
    	texts['link'] = ['Zazáložkujte si', 'Snadno nás znovu najdete a také dáte o Skinbooku vědět svým přátelům. Chybí-li Váš server, napište nám.'];
    	texts['payments'] = ['Přijímáme', 'Kromě dobírky a bankovního převodu nabízíme mnoho způsobů, jak zaplatit. Chybí-li Vám nějaký, napište nám.'];
    	texts['search'] = ['Vyhledávání', 'Hledáte nějaký konkrétní návrh nebo informace o našich výrobcích? Vyhledávání nalezne vše.'];
    	texts['cart'] = ['Nákupní košík', 'Obsahuje zboží, které chcete zakoupit. Pokud jste s jeho obsahem spokojeni, zboží jednoduše objednejte.'];
    	texts['skinbook'] = ['Můj Skinbook', 'Váš uživatelský účet, ve kterém máte přehled o svých objednávkách, stavu jejich vyřízení a spravujete svá díla.'];
    	texts['motto'] = ['Nelíbí se Vám motto?', 'Každému přijde trefné něco jiného. Rádi přidáme i Vámi navržené motto, aby jsme zasáhli každého.'];
    	texts['sticker_varieties'] = ['Barevné varianty', 'U většiny samolepek pro Vás připravujeme návrhy v různých barvách, ať si každý vybere.'];
    	texts['sticker_gallery'] = ['Galerie', 'Další obrázky zboží, ať už od nás, nebo zaslaných našimi zákazníky. U nás nekupujete zajíce v pytli.'];
    	texts['sticker_recommend'] = ['Ke zboží doporučujeme', 'Vylepšování notebooku by se mělo dělat pořádně. Nabídka vhodného zboží k aktuálně zobrazenému.'];
    	
    	$$('.showgrowl').each(function(el){
    		$(el.id).addEvents({
	  			'mouseover': function() {
  					if (el.className == 'showgrowl')
	  				{
		  				showgrowl = ( function() {
							Growl.Smoke({
								title: texts[''+el.id][0],
								text: texts[''+el.id][1],
								duration: 5
							});
							$(el.id).setProperty ('class', 'showngrowl');
	  					}).delay(250);
  					}
	  			},
  				'mouseout': function() {
  					if (showgrowl)
  					{
  						hidegrowl = $clear(showgrowl);
  					}
  				}
			});
		});
    },
    
    popup: function(element){
    	$$(element).addEvent('mouseover', function() {
	    	if ($('zoomed')) $('zoomed').remove();
	    	
	    	this.elementTop = $(this.id).getPosition().y;
			this.elementLeft = $(this.id).getPosition().x;			
			
		    this.zoom = new Element ('img', {
				'styles': {
					'position': 'absolute',
					'top': '0px',
					'cursor': 'pointer',
					'z-index': '-99',
					'display': 'none',
					'opacity': '0'
				},
		    	'src': this.getParent().rel,
	    		'id': 'zoomed'
	    	}).injectAfter(this.id);
	    	
	    	var myFx = new Fx.Style(this.zoom, 'opacity', {duration:200}).start(0,1);
			
		    this.zoom.setStyles({
				'top': (this.elementTop - 219)+'px',
				'left': (this.elementLeft - 105)+'px',
				'width': '310px',
				'height': '219px',
				'z-index': '+99',
				'display': 'block'
			});
			
	    	$(this.id).addEvent('mouseout', function () {
	    		if ($('zoomed')) $('zoomed').hide();
	    	});
	    });
    },
    
    showhide: function(el){
		if ($(el).getStyle('display') != 'none')
		{
			$(el).hide();
			return true;
		}
		$(el).show();
		return true;
	}
};
/* Spustíme všechny funkce naráz */
window.addEvent('domready', Skinbook.init);

/* Rozšíříme si funkce elementu o schování a objevení */
Element.extend({
	show : function() {
		this.setStyle("display","");
	},
	
	hide : function() {
		this.setStyle("display","none");
	}
});


/* Uživatelsky příjemné informace */
var Gr0wl = {};
Gr0wl.Base = new Class({
	options: {
		image: 'http://www.skinbook.cz/images/growl.png',
		title: '',
		text: '',
		duration: 2,
		type: ''
	},
	
	initialize: function(image) {
		this.image = new Asset.image(image, { onload: this.create.bind(this) });
		return this.show.bind(this);
	},
	
	create: function(styles) {
		this.growl_holder = new Element('div').setProperty('id','growl'+styles.type).injectInside(document.body);
		this.image.setStyles('position:absolute;display:none').setOpacity(0).injectInside(this.growl_holder);
		this.block = new Element('div').setStyles('position:absolute;display:none;z-index:999;color:#fff;font: 0.9em/1.3em Tahoma, "Lucida Grande CE", lucida, sans-serif;'+styles.div).setOpacity(0).injectInside(this.growl_holder);
		new Element('h3').setStyles(styles.h3).injectInside(this.block);
		new Element('p').setStyles(styles.p).injectInside(this.block);
	},
	
	show: function(options) {
		options = $merge(this.options, options);
		var elements = [this.image.clone(), this.block.clone()];
		elements.each(function(e, i) {
			e.injectInside(document.body);
			e.setStyles(options.position);
			if(i) e.getFirst().setHTML(options.title).getNext().setHTML(options.text);
		});
		new Fx.Elements(elements, {duration:400}).start({
			'0': { 'opacity': 0.75 }, '1': { 'opacity': 1 }
		});
		var delay = this.hide.delay(options.duration*1000, this, [elements]);
	},
	
	hide: function(elements, effect) {
		var effects = new Fx.Elements(elements, {duration:400, onComplete: function() {
			this.elements[0].remove();
			this.elements[1].empty().remove();
		}}).start({'0': effect, '1': effect });
		$$('.showngrowl').each(function(el){
			el.setProperty('class', 'showgrowl');
		});
	}
});

Gr0wl.Smoke = Gr0wl.Base.extend({
	create: function() {
		this.queue = [];
		this.visible = [];
		this.parent({
			div: 'width:298px;height:73px;',
			h3: 'margin:0;padding:10px 10px 5px 10px;font-size:13px;',
			p: 'margin:0px 10px;',
			type: 'smoke'
		});
	},
	
	show: function(options) {
		var last = this.queue.getLast(),
		delta = window.getScrollTop()+10+(last*83);
		options.position = {'top':delta+'px', 'left':'20px', 'display':'block'};
		options.type = 'smoke';
		this.queue.push(last+1);
		this.parent(options);
	},
	
	hide: function(elements) {
		this.queue.shift();
		this.parent(elements,{ 'opacity': 0 });
	}
});

Gr0wl.Bezel = Gr0wl.Base.extend({
	create: function() {
		this.i=0;
		this.parent({
			div: 'width:211px;height:206px;text-align:center;',
			h3: 'margin:0;padding:0px;padding-top:22px;font-size:14px;',
			p: 'margin:15px;',
			type: 'bezel'
		});
	},
	
	show: function(options) {
		var top = window.getScrollTop()+(window.getHeight()/2)-105,
		left = window.getScrollLeft()+(window.getWidth()/2)-103;
		options.position = {'top':top+'px', 'left':left+'px', 'display':'block'};
		options.type = 'bezel';
		this.i++;
		this.chain(this.parent.pass(options,this));
		if(this.i==1) this.callChain();
	},
	
	hide: function(elements) {
		this.queue.delay(400,this);
		this.parent(elements, { 'opacity': 0, 'margin-top': [0,50] });
	},
	
	queue: function() {
		this.i--;
		this.callChain();
	}
});

Gr0wl.Bezel.implement(new Chain);

var Growl = function(options) {
	if(Growl[options.type]) Growl[options.type].call(options);
	else Growl.Smoke(options);
};


/*
 @description		MooTools based iPhonesque switch button
 @author			Marcel Miranda Ackerman < reaktivo.com >
 @license 			MIT Style License.
 @version			0.3
 @date				2008-04-02
 @dependencies		mootools 1.11
*/
var mooSwitch = new Class({
						  
	options: {
		hide_radios: true, // hide or show the radio buttons
		hide_labels: true, // hide or show the labels
		label_position: 'inside', // display the label inside or outside the container
		label_bg: 'light',
		opacity: 1, // set the overall opacity of this.handle
		dragOpacity: 1, // Set the opacity of this.handle onDrag
		text_position: 'below', // set the text position above or below this.handle
		onStart: Class.empty, // TODO
		onComplete: Class.empty // TODO
	},
	
	initialize: function(radios, options){
		this.setOptions(options);
		params = this.options || [];
		this.duration = params.duration || 100;
		this.hide_radios = (params.hide_radios != undefined) ? params.hide_radios : true;
		params.dragOpacity = (params.dragOpacity != undefined) ? params.dragOpacity : '1';
		params.opacity = (params.opacity != undefined) ? params.opacity : '1';
		this.hide_labels = (params.hide_labels != undefined) ? params.hide_labels : false;
		this.label_position = (params.label_position != undefined) ? params.label_position : 'outside';
		if(this.label_position == 'outside' && params.label_bg == undefined){
			this.label_bg = 'light';
		} else {
			this.label_bg = (params.label_bg != undefined) ? params.label_bg : 'dark';
		}
		this.mvalue = 0;
		
		//Create Elements
		this.container = new Element('div', {'class':'switchbox'});
		this.scrollarea = new Element('div', {'class':'scrollarea'}).inject(this.container);
		this.handle = new Element('div', {'class':'handle','id':'handle_' + radios}).inject(this.scrollarea);
		this.handle.setStyle('z-index', '3').setOpacity(params.opacity);
		this.left_label = new Element('div', {'class':'label left'}).inject(this.container);
		this.right_label = new Element('div', {'class':'label right'}).inject(this.container);
		this.labels = this.container.getElements('.label');
		if(params.text_position == 'above') {
			this.labels.setStyle('z-index','10');
		} else {
			this.labels.setStyle('z-index','1');
		}
		
		//Hide Radioboxes and Labels
		this.radio_el = $$('input[name='+radios+']');
		this.container.inject(this.radio_el[this.radio_el.length-1], 'after');
		
		if(this.label_bg == 'light'){
			this.labels.addClass('light_bg');
		}
		if(this.label_position=='outside'){
			this.container.setStyle('width', this.left_label.getStyle('width').toInt() + this.scrollarea.getStyle('width').toInt() + this.right_label.getStyle('width').toInt());
			this.scrollarea.setStyle('left', this.left_label.getStyle('width').toInt());
		} else {
			this.container.setStyle('width', this.scrollarea.getStyle('width').toInt());
			if(params.text_position == 'below') {
				this.labels.setStyle('color','#fff');
			}
		}
		
		this.maxscroll = this.scrollarea.getStyle('width').toInt() - this.handle.getStyle('width').toInt();
		
		//Load handler auto sliders params
		var handle = this.handle, maxscroll = this.maxscroll, radioIndex = this.radio_el, text_position = params.text_position, label_position = this.label_position, labels = this.labels;
		var opacity = new Fx.Style($(this.handle.getProperty('id')), 'opacity', {duration:this.duration});
		var goTo = new Fx.Style(this.handle, 'left', {
			duration:this.duration, 
			onStart: function() {
				if(handle.getStyle('left').toInt() < maxscroll/2) {
					// check the left radio button
					if(label_position=='inside' && text_position=='above') {
						labels[1].setStyle('color','#555');
						labels[0].setStyle('color','#fff');
					}
				} else {
					// check the right radio button
					if(label_position=='inside' && text_position=='above') {
						labels[0].setStyle('color','#555');
						labels[1].setStyle('color','#fff');
					}
				} 
			},
			onComplete: function() {
				/*
					we only need to run this once because the onComplete for Move.Drag will run 
					this script even though	the handler will have no where to go.
				*/
				if(handle.getStyle('left').toInt() < maxscroll/2) {
					// check the left radio button
					radioIndex[0].setProperty("checked","checked");
				} else {
					// check the right radio button
					radioIndex[1].setProperty("checked","checked");
				} 
			}
		});
		
		this.radio_el.each(function(item,index){
			if(this.hide_radios) {
				item.setStyle('display', 'none');
				$$('label[for=' + item.getProperty('id') + ']').setStyle('display', 'none');
			}
			
			if(item.checked == true) { if(index) { goTo.set(maxscroll); if(this.label_position=='inside' && params.text_position=='above') { this.labels[1].setStyle('color','#555'); this.labels[0].setStyle('color','#fff'); } } else { goTo.set(0); if(this.label_position=='inside' && params.text_position=='above') { this.labels[0].setStyle('color','#555'); this.labels[1].setStyle('color','#fff'); } } };
			var opttext = $$('label[for=' + item.getProperty('id') + ']')[0].getText();
			this.container.getElements('.label')[index].setText(opttext);
		
		}.bind(this));
		
		//Execute Drag.Move initialize function
		new Drag.Move(this.handle, {
			container: this.scrollarea,
			onStart: function() {
				if(params.dragOpacity!=1) opacity.start(params.opacity,params.dragOpacity);
			},
			onComplete: function(){
				if(handle.getStyle('left').toInt() < maxscroll/2) {
					// left
					goTo.start(0);
				} else {
					// right
					goTo.start(handle.getStyle('left').toInt(),maxscroll);
				}
				if(params.dragOpacity!=1) opacity.start(params.dragOpacity,params.opacity);
			}
		});
		
		//Set Events
		this.left_label.addEvent('click', function() { goTo.start(0); });
		this.right_label.addEvent('click', function() { goTo.start(handle.getStyle('left').toInt(),maxscroll); });
		//Add Events For Original Labels And Radio Buttons
		this.radio_el.each(function(el,i) { el.addEvent('click',function() { if(i) { goTo.start(handle.getStyle('left').toInt(),maxscroll); } else { goTo.start(0); } }); });
		if(this.hide_labels){
			this.labels.setStyle('display', 'none');
		}
	}
	
});
mooSwitch.implement(new Options);


var Ticker = new Class({
	setOptions: function(options) {
		this.options = Object.extend({
			speed: 1000,
			delay: 5000,
			direction: 'vertical',
			onComplete: Class.empty,
			onStart: Class.empty,
			run: true
		}, options || {});
	},
	initialize: function(el,next,prev,options){
		this.setOptions(options);
		this.el = $(el);
		this.items = this.el.getElements('li');
		var w = 0;
		var h = 0;
		if(this.options.direction.toLowerCase()=='horizontal') {
			h = this.el.getSize().size.y;
			this.items.each(function(li,index) {
				w += li.getSize().size.x;
			});
		} else {
			w = this.el.getSize().size.x;
			this.items.each(function(li,index) {
				h += li.getSize().size.y;
			});
		}
		this.el.setStyles({
			position: 'absolute',
			top: 0,
			left: 0
		});
		this.fx = new Fx.Styles(this.el,{duration:this.options.speed,onComplete:function() {
			var i = (this.current==0)?this.items.length:this.current;
			this.items[i-1].injectInside(this.el);
			this.el.setStyles({
				left:0,
				top:0
			});
		}.bind(this)});
		this.current = 0;
		if (this.options.run)
		{
			this.next();
		}
		$(next).addEvent('click', function(){this.next()}.bind(this));
		$(prev).addEvent('click', function(){this.prev()}.bind(this));
		$(el).addEvent('mouseover', function(){if (this.todo) $clear(this.todo)}.bind(this));
		$(el).addEvent('mouseout', function(){
			this.todo = function() {
				if (this.options.run)
				{
					this.next()
				}
			}.bind(this).delay(this.options.delay+this.options.speed);
		}.bind(this));
	},
	next: function() {
		if (this.todo) $clear(this.todo);
		this.current++;
		if (this.current >= this.items.length) {
			this.current = 0;
		}
		var pos = this.items[this.current];
		this.fx.start({
			left: -pos.offsetLeft
		});
		if (this.options.run)
		{
			this.todo = function() {this.next()}.bind(this).delay(this.options.delay+this.options.speed);
		}
	},
	prev: function() {
		if (this.todo) $clear(this.todo);
		this.current--;
		if (this.current <= 0) {
			this.current = (this.items.length-1);
		}
		var pos = this.items[this.current];
		this.fx.start({
			left: +pos.offsetLeft
		});
		this.current++;
		if (this.options.run)
		{
			this.todo = function() {this.next()}.bind(this).delay(this.options.delay+this.options.speed);
		}
	}
});

