/**
 * Implement element getSlide method to get/create silder effect of it
 */
Element.implement({
	slideFx : null,
	
	getSlide : function(){
		if (!$chk(this.slideFx)) {
			this.slideFx = new Fx.Slide(this,{
				link: 'cancel',
				duration: 500
			});
		}
		return this.slideFx;
	}
});

/**
 * VerticalTab
 */
var VillamVerticalTab = new Class({
	Implements: [Options , Events],
	
	options : {
		tabSelector : null,
		tabTitlesSelector : null,
		tabContentsSelector : null,
		duration : 350,
		transition : Fx.Transitions.Quint.easeInOut,
		minHeight : 0,
		selectedTitleStyle : {
		},
		unSelectedTitleStyle : {
		}
	},
	
	tabs : null,
	tabContentHeights : null,
	
	// FXs
	fxContent : null,
	
	fxTitle : null,
	
	initialize : function (options){
		this.setOptions(options);
		this.tabs = $(document).getElements( this.options.tabSelector );
		this.tabContentHeights = {};
		this.fxContent = new Fx.Elements( $(document).getElements( this.options.tabSelector + " " + this.options.tabContentsSelector ) , {
			wait: false, 
			duration: this.options.duration, 
			transition: this.options.transition 
		});
		this.fxTitle = new Fx.Elements( $(document).getElements( this.options.tabSelector + " " + this.options.tabTitlesSelector ) , {
			wait: false, 
			duration: this.options.duration, 
			transition: this.options.transition 
		});		
		this.createTabs();
	},
	
	showTab : function(id){
		this.tabs.each(function(tab){
			if (tab.get('id') == id){
				title = tab.getElement(this.options.tabTitlesSelector);
				title.fireEvent('click');
			}
		}.bind(this));
	},
	
	createTabs : function(){
		this.tabs.each(function(tab , i){
			var tabTitle = tab.getElement(this.options.tabTitlesSelector);
			var tabContent = tab.getElement(this.options.tabContentsSelector);
			if ($chk(tabTitle) && $chk(tabContent)){
				this.tabContentHeights[i] = tabContent.getCoordinates().height;
				tabContent.setStyle("height" , this.options.minHeight );
				tabTitle.setStyle("cursor" , "pointer");
				// click on title
				tabTitle.addEvent('click' , function( event ){
					var fxContentOptions = {};
					var fxTitleOptions = {};
					this.tabs.each(function (tabj , j){
						var h = tabj.getElement(this.options.tabContentsSelector).getCoordinates().height;
						if (i != j){
							if (h != this.options.minHeight) {
								fxContentOptions[j] = { 'height' : [h, this.options.minHeight] };
							}
							fxTitleOptions[j] = this.options.unSelectedTitleStyle;
						} else {
							fxContentOptions[j] = { 'height' : [ h , this.tabContentHeights[j] ] };
							fxTitleOptions[j] = this.options.selectedTitleStyle;
							this.fireEvent('show' , tabj);
						}
					}.bind(this));
					this.fxContent.start(fxContentOptions).chain(function(){
						tabContent.setStyle("height" , "auto");
					}.bind(this));
					this.fxTitle.start(fxTitleOptions);
				}.bind(this));
				// select title
				var titleFx = new Fx.Morph(tabTitle, {duration:200, wait:false});
				tabTitle.addEvent('mouseenter' , function( event ){
					if (tabContent.getStyle("height").toInt() != this.options.minHeight) return;
					titleFx.start(this.options.selectedTitleStyle);
				}.bind(this));
				// unselect title
				tabTitle.addEvent('mouseleave' , function( event ){
					if (tabContent.getStyle("height").toInt() != this.options.minHeight) return;				
					titleFx.start(this.options.unSelectedTitleStyle);
				}.bind(this));
			}
		}.bind(this));
	}
});

var VillamHorizontalTab = new Class({
	Implements : [Options, Events],
	
	options : {
		tabGroupSelector : null,
		titleSelector: null,
		contentSelector : null,
		activeTitleClass : 'active',
		inactiveTitleClass : 'inactive',
		selectedNr : 0
	},
	
	titles: [],
	
	contents : [],
	
	contentHeights : [],
	
	switchTo : function(nr){
		this._inactivateTab(this.options.selectedNr);
		this.options.selectedNr = nr;
		this._activateTab(this.options.selectedNr);
		this.fireEvent('select' , this.options.selectedNr);
	},
	
	_inactivateTab : function(nr){
		this.titles[nr].removeClass(this.options.activeTitleClass);
		this.titles[nr].addClass(this.options.inactiveTitleClass);
		this._hideContent(this.contents[nr]);
	},
	
	_activateTab : function(nr){
		this.titles[nr].addClass(this.options.activeTitleClass);
		this.titles[nr].removeClass(this.options.inactiveTitleClass);
		this._showContent(this.contents[nr]);
	},
	
	_showContent : function(content){
		content.setStyle('display' , 'block');
	},
	
	_hideContent : function(content){
		content.setStyle('display' , 'none');
	},
	
	initialize : function(options){
		this.setOptions(options);
		$(document).getElements(this.options.tabGroupSelector).each(function(tabGroup){
			// get titles and contents
			this.titles = tabGroup.getElements(this.options.titleSelector);
			this.contents = tabGroup.getElements(this.options.contentSelector);
			// initialize titles and content
			this.contents.each(function(content , i){
				this.contentHeights[i] = content.getSize().y;
				if (i == this.options.selectedNr){
					this._activateTab(i);
				} else {
					this._inactivateTab(i);	
				}
			}.bind(this));
			// add title action
			this.titles.each(function(title , i){
				var nr = i;
				title.addEvent('click' , function(){
					this.switchTo(nr);
				}.bind(this));
			}.bind(this));
		}.bind(this));
	}
});

/**
 * Villam alert
 */
var MESSAGE_OK 			= 'MESSAGE_OK';
var MESSAGE_INFO 		= 'MESSAGE_INFO';
var MESSAGE_QUESTION 	= 'MESSAGE_QUESTION';
var MESSAGE_WARNING 	= 'MESSAGE_WARNING';
var MESSAGE_ERROR 		= 'MESSAGE_ERROR';

var MessageBox = new Class({
	Implements : Options,

	defaultOptions : {
		type : MESSAGE_WARNING,
		title : 'Message box title',
		message : 'Message box message',
		buttons : [
			{ title : VText('Ok') }
		]
	},
	
	options : {},
	
	container : null,
	
	showed : false,
	
	_getContainer : function(){
		if ($chk(this.container)) return this.container;
		this.container = new Element('div' , {
			'class' : 'villam-popup-container',
			'html' : '<div class="villam-popup">' +
					 '<div class="villam-popup-top">' +
					 '  <h1></h1>' +
					 '  <div class="clearer"></div>' +
					 '  <div class="villam-popup-ico"></div>' +
					 '  <div class="villam-popup-message"></div>' +					 
					 '  <div class="villam-popup-buttons">' +
					 '    <div id="buttons"></div>' +
					 '    <div class="clearer"></div>' +
					 '  </div>' +
					 '  <div class="clearer"></div>' +					 
					 '</div>' +
					 '<div class="villam-popup-bottom"></div>' +
					 '</div>',
			'styles' : {
				'display' : 'none'
			}
		});
		this.container.inject(document.body);
		return this.container;
	},
	
	initialize : function(){
		$(window).addEvent('scroll' , function(){
			this._refreshContainerPosition.run(null , this);
		}.bind(this));
		$(window).addEvent('resize'  , function(){
			this._refreshContainerPosition.run(null , this);
		}.bind(this));
	},
	
	_getButtonContainer : function(){
		return this._getContainer().getElement(".villam-popup-buttons #buttons");
	},
	
	_addButton : function(title , onClickCallback){
		var button = new Element('h2' , {
			'events' : {
				'click': function(){
					res = true;
					if ($defined(onClickCallback) && $chk(onClickCallback)) {
						res = onClickCallback.run();
					}
					if (res != false) {
						this._hideContainer();
					}
				}.bind(this)
			}
		});
		new Element('span' , {
			'html' : title
		}).inject(button);
		button.inject(this._getButtonContainer() , 'top');
	},
	
	_refreshContainerPosition : function(){
		if (!this.showed) return;
		windowSize = $(window).getSize();
		windowScroll = $(window).getScroll();		
		this._getContainer().setStyles({		
			'height' : windowSize.y,
			'left': windowScroll.x,
			'top' : windowScroll.y
		});
		var popup = this._getContainer().getElement('.villam-popup');
		popup.setStyle('top' , ( windowSize.y - popup.getSize().y ) / 2 );
	},
	
	_showContainer : function(){
		this.options = $extend(this.defaultOptions , this.options);
		this._getButtonContainer().innerHTML = '';
		this.options.buttons.each(function(button){
			if (button == undefined) return;
			this._addButton(button.title , $pick(button.onClick , null));
		}.bind(this));		
		this._getContainer().setStyles({
			'display' : 'block'
		});
		this.showed = true;
		this._refreshContainerPosition();
		this._getContainer().getElement('.villam-popup').addClass(this.options.type);
		this._getContainer().getElement('.villam-popup-message').innerHTML = this.options.message;
		this._getContainer().getElement('.villam-popup-top h1').innerHTML = this.options.title;
	},
	
	_hideContainer : function(){
		this._getContainer().setStyles({
			'display' : 'none' 
		});
		this._getContainer().set('class' , 'villam-popup-container');
		this._getContainer().getElement('.villam-popup').set('class' , 'villam-popup');	
		this.showed = false;
	},
	
	show : function(options){
		this.setOptions(options);
		this._showContainer();
	}
});

/**
 * Villam preloader
 */
// Major version of Flash required
var requiredMajorVersion = 8;
// Minor version of Flash required
var requiredMinorVersion = 0;
// Minor version of Flash required
var requiredRevision = 0;

var VillamPreloader = new Class({
	contentContainerId : null,
	
	preloaderContainerId : null,
	
	fx : null,
	
	options : {
		transition : Fx.Transitions.Expo.easeIn ,
		duration : 300
	},
	
	initialize : function(contentContainerId , preloaderContainerId){
		this.preloaderContainerId = preloaderContainerId;
		this.contentContainerId = contentContainerId;
		
		window.addEvent('domready' , function(){
			this.showPreloader();
		}.bind(this));
		window.addEvent('load' , function(){
			this.showContent();
		}.bind(this));		
	},
	
	showPreloader : function(){
		//size = $(window).getSize();
		//$(this.preloaderContainerId).setStyle('padding-top' , size.y / 2 - 80);
	},
	
	showContent : function(){
		var container = $(this.preloaderContainerId);
		if (!$chk(container)) return;
		container.dispose();
		this.fx = new Fx.Morph($(this.contentContainerId) , {
			transition : this.options.transition,
			duration: this.options.duration
		});
		$(this.contentContainerId).setStyles({
			'visibility' : 'visible',
			'opacity' : '0'
		});		
		this.fx.start({
			'opacity' : '1'
		});
	}
})

/**
 * Villam box
 */
VillamBoxFxList = [];
var VillamBoxFx = new Class({
	Implements: [Options , Events],
	
	options: {
		duration: 300,
		transition : Fx.Transitions.Expo.easeOut,
		scrollWindow : true,
		scrollDuration : 2500,
		scrollTransition : Fx.Transitions.Expo.easeOut,
		scrollTo: null
	},	
	
	box : null,
	
	fx : null,
	
	scrollFx : null,
	
	opened : true,
	
	initialize : function(content , options){
		if ($chk(options)){
			this.setOptions(options);
		}
		this.content = content;
		this.box = new Element('div',{
			'styles' : {
				'overflow' : 'hidden',
				'height' : this.content.getSize().y,
				'margin' : 0,
				'padding' : 0
			}
		}).inject(this.content , 'before');
		this.content.inject(this.box);
		this.fx = new Fx.Morph(this.box, {
			duration: this.options.duration, 
			transition: this.options.transition
		});
		
		if (this.options.scrollWindow){
			this.scrollFx = new Fx.Scroll(window, { 
				wait: false, 
				duration: this.options.scrollDuration,
				transition: this.options.scrollTransition 
			});
		};
		
		VillamBoxFxList.push(this);		
	},
	
	_scroll: function(){
		if (this.options.scrollWindow && $chk(this.scrollFx)){
			VillamBoxFxList.each(function(villamBoxFx){
				villamBoxFx.stopScroll();
			});
			this.scrollFx.toElement($chk(this.options.scrollTo) ? this.options.scrollTo : this.box);
		}		
	},
	
	stopScroll : function(){
		if (this.options.scrollWindow && $chk(this.scrollFx)){
			this.scrollFx.cancel();
		}
	},
	
	isOpened : function(){
		return this.opened;
	},
	
	hide: function(){
		this.opened = false;
		this.box.setStyle('height' , 0);
		this.fireEvent('hide');	
	},
	
	show: function(){
		this.opened = true;
		this.box.setStyle('height' , this.content.getSize().y);	
		this.fireEvent('show');
	},	
	
	close : function(){
		this.opened = false;
		this.fx.cancel();
		this.fx.start({
			'height' : 0
		}).chain(function(){
			this.fireEvent('close');
		}.bind(this));
	},
	
	open : function(){
		this.opened = true;
		this.fx.cancel();
		this.fx.start({
			'height' : this.content.getSize().y
		}).chain(function(){
			this.box.setStyle('height' , 'auto');
			this.fireEvent('open');
		}.bind(this));
		this._scroll();
	},
	
	toggle : function(){
		if (this.opened){
			this.close();
		} else {
			this.open();
		}
	}
});

/**
 * Villam tooltip 
 */

// Mootools Tips bug repaired...
Tips.prototype.fireForParent = function(event, element){
		if (!element) return;
		parentNode = element.getParent();
		if (parentNode == document.body) return;
		if (parentNode.retrieve('tip:enter')) parentNode.fireEvent(event,'mouseenter');
		else this.fireForParent(event, parentNode);
	};

window.addEvent('domready', function() {
	// store titles and text
	$$('.has-villam-tooltip').each(function(element,index) {
		var content = element.get('title').split('::');
		element.store('tip:title', content[0]);
		element.store('tip:text', content[1]);
	});
	
	// create the tooltips
	var villamTooltip = new Tips('.has-villam-tooltip',{
		className: 'villam-tooltip',
		fixed: false,
		hideDelay: 50,
		showDelay: 50,
		offset: {x: 5, y: 5}
	});

	// fade in and out
	villamTooltip.addEvents({
		'show': function(tip) {
			tip.fade('in');
		},
		'hide': function(tip) {
			tip.fade('out');
		}
	});

	// IE png fix
	villamTooltip.tip.getElement('.tip-top').innerHTML = '<!-- -->';
	if (window.supersleight){
		supersleight.fixBackground(villamTooltip.tip.getElement('.tip-top'));
		supersleight.fixBackground(villamTooltip.tip.getElement('.tip'));
		supersleight.fixBackground(villamTooltip.tip.getElement('.tip-bottom'));
	}
});

/**
 * Inteligent AJAXCall class
 * 
 * Element with class "ajax-ico-[TASKNAME]" will be hidden while ajax call is in
 * progress and "this.options.ico" will be showed.
 * 
 * Element with class "ajax-ready-ico-[TASKNAME]" will be showed while ajax call is 
 * in progress and will be hidden when ajax is not in progress. 
 */
var AJAXCall = new Class({
	Implements: [Events , Options, Chain],
	
	icoContainers : [],
	
	icoRelatedElements : [],
	
	options: {
		ico					: '/images/ajax-loader.gif',
		url					: '/index.php',
		method				: 'post',
		json				: true,
		relatedContainers	: null,
		data				: {
			'controller' : 'ajax'
		}
	},
	
	optionsClone : null,
	
	request: null,
		
	initialize : function(options){
		// extend options
		this.setOptions(options);
		if (!$chk(this.options.relatedContainers)) this.options.relatedContainers = [ $(document) ];
		this._createRequest();		
		this._insertICO();
		this._collectICO();
		this._hideICO();
	},
	
	_createRequest : function(){
		this.optionsClone = $extend({} , this.options);
		this.optionsClone.onComplete = function(response){
			this._hideICO();
			this.fireEvent('complete' , this.options.json ? JSON.decode(response) : response);
			this.callChain(this.options.json ? JSON.decode(response) : response);
		}.bind(this);
		this.optionsClone .onRequest = function(){
			this._showICO();
			this.fireEvent('request');		
		}.bind(this);		
		this.request = new Request(this.optionsClone);
	},
	
	_getTranslationParameters : function(){
    	var json = {};
    	this.options.relatedContainers.each(function(container){
			container.getElements('input, select, textarea', true).each(function(el){
				if (!el.name || el.type == 'submit' || el.type == 'reset' || el.type == 'file') return;
				var value = (el.tagName.toLowerCase() == 'select') ? Element.getSelected(el).map(function(opt){
					return opt.value;
				}) : ((el.type == 'radio' || el.type == 'checkbox') && !el.checked) ? null : el.value;
				$splat(value).each(function(val){
					if (typeof val != 'undefined') json[el.name] = val;
				});
	    	});
		});
    	return json;
		
		/*
		var names = [];
		var values = [];
		this.options.relatedContainers.each(function(container){
			container.getElements('input').each(function(e){
				names.push(e.get('name'));
				values.push(e.get('value'));
			});
		});
		return values.associate(names);	
		*/
	},
	
	_insertICO : function(){
		className = "ajax-ico-" + this.request.options.data.task;
		this.icoRelatedElements = $(document).getElements("." + className);
		this.icoRelatedElements.each(function(e){
			e.removeClass(className);
			size = e.getSize();
			div = new Element('div', {
				'styles' : {
					'width' : size.x,
					'height': size.y
				} 
			});
			new Element('img' , {
				'src' : this.options.ico
			}).inject(div);
			div.inject(e,'before');
			this.icoContainers.push(div);
		}.bind(this));
	},
	
	_collectICO : function(){
		className = "ajax-ready-ico-" + this.request.options.data.task;
		this.icoContainers = $extend( this.icoContainers , $(document).getElements("." + className) );
	},
	
	_hideICO : function(){
		this.icoRelatedElements.each(function(e){
			e.setStyle('display' , 'block');
		});
		this.icoContainers.each(function(e){
			e.setStyle('display' , 'none');
		});		
	},	
	
	_showICO : function(){
		this.icoRelatedElements.each(function(e){
			e.setStyle('display' , 'none');
		});
		this.icoContainers.each(function(e){
			e.setStyle('display' , 'block');
		});		
	},
	
	send: function(data , getFormParameters){
		// cancel previous request
		this.request.cancel()		
		// set default argument value
		if (!$chk(getFormParameters)){
			getFormParameters = true;
		}
		// set request data
		requestData = {};
		if (getFormParameters) requestData = $extend(requestData , this._getTranslationParameters());
		if ($chk(data)) requestData = $extend(requestData , data);
		requestData = $extend(requestData , this.options.data);
		this.request.options.data = $extend(this.request.options.data, requestData);
		// send request
		this.request.send();
		return this;
	},
	
	setData : function(data){
		this.options.data = $extend(this.options.data , data);
	}
});

/**
 * Villam Autocompleter
 */
VillamAutocompleter = new Class({
	Extends : Autocompleter.Request.JSON,
	
	initialize: function(el, options) {
		options = $merge({
			'postVar': 'autocompleter_value',
			'delay' : 150,
			'postData' : {
				'autocompleter_type' : '',
				'task' : 'autocompleter',
				'controller' : 'ajax'
			}
		} , options);
		this.parent(el, '/index.php', options);
	}
});

/**
 * Villam JS
 */
new VillamPreloader('villam-container','villam-preloader');


/**
 * Change input type
 */
function changeInputType(oldObject, oType) {
	var newObject = document.createElement('input');
	newObject.type = oType;
	if(oldObject.size) newObject.size = oldObject.size;
	if(oldObject.value) newObject.value = oldObject.value;
	if(oldObject.name) newObject.name = oldObject.name;
	if(oldObject.id) newObject.id = oldObject.id;
	if(oldObject.className) newObject.className = oldObject.className;
	if(oldObject.alt) newObject.alt = oldObject.alt;
	if(oldObject.onblur) newObject.onblur = oldObject.onblur;
	if(oldObject.onfocus) newObject.onfocus = oldObject.onfocus;
	oldObject.parentNode.replaceChild(newObject,oldObject);
	return newObject;
}

/**
 * Miscelaneous instances
 */
window.addEvent('domready' , function(){	
	// format email input field
	var input = $(document).getElement('.villam-login-box input[name=email]');
	if ($chk(input)) {
		input.value = VText('loginemail');
		input.addEvents({
			'focus': function(){
				if (this.value == VText('loginemail')) 
					this.value = '';
			},
			'blur': function(){
				if (this.value == '') 
					this.value = VText('loginemail');
			}
		});
	}
	
	// format password input field
	input = $(document).getElement('.villam-login-box input[name=password]');
	if ($chk(input)) {
		input = changeInputType(input, 'text');
		input.value = VText('loginpassword');
		input.onfocus = function(){
			if (this.value == VText('loginpassword')) {
				var newthis = changeInputType(this, 'password');
				newthis.value = '';
				newthis.focus();
			}
		};
		input.onblur = function(){
			if (this.value == '') {
				var newthis = changeInputType(this, 'text');
				newthis.value = VText('loginpassword');
			}
		};
	}	
});

/****************************
 * LOGIN BOX
 ****************************/
ajaxLogin = new AJAXCall({
	'data' : {
		'task' : 'loginuserbox'
	}
});	

/****************************
 * MAIN MESSAGE BOX
 ****************************/	
messageBox = new MessageBox();