Event.observe(document, 'dom:loaded', function(){

	//inicjalizacja
	UI.init();

});

var UI;
if (typeof UI == "undefined") UI = {};

UI.init = function(){

	//katalog produktow
	new UI.DropDown('nav-product-catalogue', 'nav-product-cat-exp');

	//porady, inspiracje...
	new UI.DropDown('nav-site-sections', 'sub-nav-site-sections');

	
	//4 dzialy...
	new UI.DropDown('budujesz', 'nav-product-cat-exp2');
	new UI.DropDown('remontujesz', 'nav-product-cat-exp3');	
	new UI.DropDown('urzadzasz', 'nav-product-cat-exp4');
	new UI.DropDown('ogrod', 'nav-product-cat-exp5');
	
	
	//wyszukiwarka
	//new UI.SearchTypeDD();

	//labele w inputach
	new UI.InputLabel($$('input.hint'));

	//custom selects
	var selects = new UI.SelectBoxController();

	/*
	var s = selects.getElementById('prod-colors');
	s.selectMe($('prod-colors'), 1);
	*/

	var mapContainer = $('canvas-map');
	//wojewodztwa na mapie, wywola sie tylko gdy znajdzie odpowiedniego diva
	if(mapContainer){
		new UI.MapHighlighter({onClick: pokazWojewodztwoTest});
	}

	var slider = new UI.CarouselController();

}

function pokazWojewodztwoTest(vdshipName, data){
	alert(vdshipName + ', ' + data);
	//definiowane w map-paths.js
}

/***************************************/
/************ dropdown menu ************/
UI.DropDown = Class.create({
	initialize:function(containerId, menuId, options){
		var t = this;
		this.defaults = {
			anim: {
				duration:0.3,
				queue:'end',
				limit:2,
				afterFinish: function(){
					t.anim = false;
				}
			}
		};
		this.opts = Object.extend(this.defaults, options);

		//kontener z nawigacja
		this.container = $(containerId);

		//menu pokazywane po najechaniu na link z klasa "ui-dd-trigger" !!!
		this.trigger = this.container.select('.ui-dd-trigger').first();

		//dropdowna pokazywany po najechaniu
		this.dropdown = $(menuId);

		this.trigger.observe('mouseover', this.showDropdown.bindAsEventListener(this));
		this.container.observe('mouseout', this.hideDropdown.bindAsEventListener(this));

	},

	showDropdown: function(e){
		e.stop();
		//if(!this.anim){
			this.anim = true;
			new Effect.Appear(this.dropdown, this.opts.anim);
		//}
	},

	hideDropdown:function(e){
		e.stop();
		var id = this.container.id;
		try{
			var relatedElement = e.relatedTarget || e.toElement;
			if(relatedElement && !relatedElement.up('#' + id)){
				//if(!this.anim){
					this.anim = true;
					new Effect.Fade(this.dropdown, this.opts.anim);
				//}
			}
		}catch(ex){
			/* wyjatek wystapi po zjechaniu myszka na XUL element, np srodek inputa */
		}

	}

})

/******************************************************************/
/************ DropDown do wyboru rodzajow wyszukiwania ************/
/*UI.SearchTypeDD = Class.create({
	initialize:function(options){
		var t = this;
		this.defaults = {
			formId: 'search_mini_form'
		};
		this.opts = Object.extend(this.defaults, options);
		this.isOpen = false;

		this.form = $(this.opts.formId);
		this.formInput = this.form.select('input.text').first();
		this.select = this.form.select('select').first();
		this.options = this.select.select('option');
		this.label = this.form.select('label.hint').first();

		//dodajemy dd
		this.dropdown = this.appendDropDown();

		//inicjalizacja observerow
		this.initObservers();

	},

	initObservers: function(){
		var t = this;
		//dla formularza
		this.form.observe('submit', this.onFormSubmit.bindAsEventListener(this));

		//dla elementow dropdowna
		this.dropdown.select('li').each(function(li, index){
			li.observe('click', t.onTypeSelection.bindAsEventListener(t));
		});

		//po kliknieciu gdziekolwiek poza dd - ukrywamy
		document.observe('click', this.hideDropdown.bindAsEventListener(this));

	},

	//po odpaleniu submit w formularzu
	onFormSubmit: function(e){
		e.stop();
		this.showDropdown();
	},

	//dodajemy dropdowna do formularza
	appendDropDown: function(){
		var t = this;
		var lis = '';
		//pobieramy text z opcji w selekcie
		this.options.each(function(opt, index){
			lis += '<li class="search-type ' + (index==0?'first selected':'') + '" id="search-type-' + index + '">' + opt.innerHTML + '</li>';
		});

		//wstawiamu dropdowna do formularza
		var html = '<ul id="' + this.opts.formId + '-type-dropdown" class="search-type-dropdown" style="display:none;">' + lis + '</ul>'
		this.form.insert(html);

		//zwracamy referencje dropdowna (DOM)
		var dd = $(this.opts.formId + '-type-dropdown');

		return dd;
	},

	//pokazujemy
	showDropdown: function(){
		var t = this;
		this.dropdown.appear({duration:0.3,afterFinish:function(){t.isOpen=true;}});
	},

	//ukrywamy
	hideDropdown: function(e){
		var t = this;
		if(this.isOpen) this.dropdown.fade({duration:0.3,afterFinish:function(){t.isOpen=false;}});
	},

	//po wyborze typu z dropdowna
	onTypeSelection:function(e){
		e.stop();

		//ustawiamy ikonke na zaznaczonym LI
		var el = Event.element(e);
		var type = this.getTypeFromEl(el);
		el.siblings().invoke('removeClassName', 'selected');
		el.addClassName('selected');

		//przestawiamy tresc labela
		var label = $('ui-label-' + this.formInput.id);
		if(label){
			label.innerHTML = el.innerHTML;
		}

		//ustawiamy wybrany typ w SELECT
		this.setType(type);

		//submitujemy formularz jezeli pole niepuste
		this.submitForm();
		this.hideDropdown();
	},

	//submituje form
	submitForm: function(){
		if(this.formInput.value!==''){
			this.form.submit();
		}else{
			this.formInput.focus();
		}
	},

	//zwraca index wybranego typu wyszukiwania (odpowiada selectedIndex w selekcie)
	getTypeFromEl:function(link){
		var idParts = link.id.split('-');
		var type = idParts[idParts.length-1];
		return type;
	},

	//ustawia typ wyszukiwania w selekcie
	setType: function(type){
		this.select.selectedIndex = type;
	}

})
*/

/**************************************/
/************ input labels ************/
UI.InputLabel = {};
UI.InputLabel = Class.create({

	initialize: function(inputs, options){
		var self = this;
		this.defaults = {
			offsetLeft: 0,
			offsetTop: 0
		};
		this.options = Object.extend(this.defaults, options);

		this.inputs = inputs;

		if(!this.inputs.length) return;

		this.inputs.each(function(input,id){

			input.identify();
			var label = self.createLabel(input);
			if(input.getValue() == '') {
				label.show();
			}

			//focus ukrywa label-a
			input.observe('focus', function(event){
				$('ui-label-' + this.id).hide();
				this.addClassName('ui-inputlabel-focused');
			});

			//blur pokazuje label-a jezeli nic nie wpisano
			input.observe('blur', function(event){
				if(this.getValue()==''){
					$('ui-label-' + this.id).show();
				}
				this.removeClassName('ui-inputlabel-focused');
			});
		});
	},

	//tworzy label i pozycjonuje go nad inputem
	createLabel: function(input){
		//var label = new Element('label', { 'for': input.id, 'id': 'ui-label-' + input.id, 'class': 'ui-input-label' }).update(input.readAttribute('title')).setStyle({position:'absolute'});
		var label = '<label for="' + input.id + '" id="ui-label-' + input.id + '" class="ui-input-label" style="position:absolute;">' + input.readAttribute('title') + '</label>';
		input.insert({
			'after': label
		});
		var label = $('ui-label-' + input.id);
		//kopiowanie pozycji z input-a do label-a
		try{
			label.clonePosition(input, {offsetLeft: this.options.offsetLeft, offsetTop: this.options.offsetTop});
		}catch(e){
			label.clonePosition(input, {offsetLeft: this.options.offsetLeft, offsetTop: this.options.offsetTop});
		}


		var padding = input.getStyle("paddingLeft").slice(0,-2);
		if(padding > 0) {
			var labelLeft = label.getStyle("left").slice(0,-2);
			var labelWidth = label.getStyle("width").slice(0,-2);

			var l = Math.max(0,(parseInt(labelLeft)+parseInt(padding)));
			var w = Math.max(0,(parseInt(labelWidth)-parseInt(padding)));
			label.setStyle({left:l+'px',width:w+'px'});
		}


		//srodkowanie tekstu w pionie
		var h = label.getHeight();
		label.setStyle({'lineHeight': h + 'px'});

		label.hide();
		return label;
	}
});

/* controller pomagajacy w obsludze customowych selectow */
UI.SelectBoxController = {};
UI.SelectBoxController = Class.create({

	initialize:function(options){

		this.defaults = {
			elementsSelector: '.select'
		};
		this.options = Object.extend(this.defaults, options);

		//wszystkie selecty na stronie
		this.selects = $$(this.options.elementsSelector);

		// hashmapa przechowujaca referencje do kazdego selectboxa
		this.selecboxes = new Hash();

		this.initSelectBoxes();

	},

	initSelectBoxes: function(){
		var t = this;

		this.selects.each(function(select, index){
			var id = select.identify();

			if(typeof UI.SelectBox === 'undefined'){
				alert('UI.SelectBoxController: You need to include selectbox.js in your page!!!');
				return;
			}

			var selectbox = new UI.SelectBox({id: id});

			t.selecboxes.set(id, selectbox);
		});
	},

	getElementById: function(id){
		return this.selecboxes.get(id);
	}
	/*,
	setOnChange: function(id, onChange){
		this.getElementById(id).options.onChange = onChange;
	}*/

});

/*  */
UI.MapHighlighter = {};
UI.MapHighlighter = Class.create({

	initialize: function(options){
		this.defaults = {
			mapContainerId: 'canvas-map',
			hoverColor: '#fff858',
			//definicja w map-paths.js
			mapPaths: mapPaths,
			raphAttributes: {
				fill: '#e9e9e9',
				stroke: '#ffffff',
				'stroke-width': 0,
				'stroke-linejoin': 'round'
        	},
			onClick: function(){}
		};
		this.options = Object.extend(this.defaults, options);

		this.raphael = Raphael(this.options.mapContainerId, 240, 230);
		//var attributes =
		this.vdships = new Array();
		this.raphVdships = new Array();

		this.initRaphaelPaths();
		this.initObservers();

		this.selected = null;

	},

	initRaphaelPaths: function(){
		var o = this.options;
		for (var vdship in o.mapPaths) {
			var raphVdship = this.raphael.path(o.mapPaths[vdship].path);
			raphVdship.attr(o.raphAttributes);
			this.raphVdships[raphVdship.id] = raphVdship;

			this.vdships[raphVdship.id] = o.mapPaths[vdship];
		}
	},

	initObservers: function(){
		var t = this, o = this.options;
		this.raphVdships.each(function(v, index){
			var path = v;
			path.hover(function(event){
				this.animate({
					fill: o.hoverColor
				}, 300);
			}, function(event){
				if(t.selected != this.id){
					this.animate({
						fill: o.raphAttributes.fill
					}, 300);
				}
			}).click(function(event){

				//zaznacz
				this.animate({
					fill: o.hoverColor
				}, 300);

				//odznacz poprzedni
				if(t.selected != null){
					var previous = t.raphVdships[t.selected];
					previous.animate({
						fill: o.raphAttributes.fill
					}, 300);
				}
				t.selected = this.id;

				//wywolaj callback
				var name = t.vdships[this.id].name, data = t.vdships[this.id].data;
				t.options.onClick(name, data);

			})
		})
	}

});


UI.CarouselController = {};
UI.CarouselController = Class.create({

	initialize:function(options){

		this.defaults = {
			elementsSelector: '.carousel-container',
			carouselOptions: {
				previousButton: '.btn-prev',
				nextButton: '.btn-next',
				scrollInc: 6,
				container: '.carousel'
			}
		};
		this.options = Object.extend(this.defaults, options);

		//wszystkie kontenery na stronie
		this.elements = $$(this.options.elementsSelector);

		this.carousels = new Hash();

		this.initCarousels();

	},

	initCarousels: function(){
		var t = this;

		this.elements.each(function(carouselEl, index){
			var id = carouselEl.identify();

			if(typeof UI.Carousel === 'undefined'){
				alert('UI.CarouselController: You need to include carousel.js in your page!!!');
				return;
			}

			t.options.carouselOptions.scrollInc = t.getScrollIncrement(carouselEl);

			var carousel = new UI.Carousel(id, t.options.carouselOptions);
			t.carousels.set(id, carousel);
		});
	},

	getScrollIncrement: function (carouselEl){
		var scrollInc = parseInt(carouselEl.className.split('carousel-inc-')[1].split(' ')[0], 10) || this.options.carouselOptions.scrollInc;
		return scrollInc;
	},

	getElementById: function(id){
		return this.carousels.get(id);
	}

});
