var CheckboxController = Class.create({

	initialize: function(id, allSelectorValue) {
		var container = $(id);
		var allSelector = container.select('input[value="' + allSelectorValue + '"]')[0];
		var allInputs = container.select('input');
		var otherInputs = container.select('input:not([value="' + allSelectorValue + '"])');
		
/*
		if (allSelector.checked)
		{
			allInputs.each(function(element){
				element.checked = true;
			});
		}
*/

		allSelector.observe('click', function(){

			if (this.checked)
				otherInputs.each(function(element){
					element.checked = false;
				});
		});

		otherInputs.each(function(element){
			element.observe('click', function(){
				allSelector.checked = false;
			});
		});

	}

});



var InputDefaultValue = Class.create({

	initialize: function(fieldId, defaultValue) 
	{
		field = $(fieldId);
		if (!field)
			return false;

		field.observe('blur', function(){
			if (!$F(this))
			{
				this.value = defaultValue;
				this.addClassName('emptyValue');
			}
		});

		field.observe('focus', function(){
			if ($F(this) == defaultValue)
			{
				this.value = '';
				this.removeClassName('emptyValue');
			}
		});

		if (!$F(field))
		{
			field.value = defaultValue;
			field.addClassName('emptyValue');
		}
	}

});




var TabMenuFromDL = Class.create({

	initialize: function(fieldId, options)
	{
		this.id = Math.round(100000 * Math.random());
		
		this.dl = $(fieldId);
		this.dts = this.dl.select('dt');
		this.count = this.dts.length;

		this.ids = new Array();
		this.dls = new Array()

		for (var i=0; i<this.count; i++)
		{
			this.ids.push(this.dts[i].next().id);
			this.dls.push(this.dts[i].next());
		}

		this.readOptions(options);
		this.createTabs();
		
		this.show(this.index);
	},
	
	
	readOptions: function(options)
	{
		if (!options)
		{
			this.index = 0;
			return;
		}

		this.index = (options.index) ? options.index : 0;
		if (options.prevButton)
			this.prevButton = $(options.prevButton);
		if (options.nextButton)
			this.nextButton = $(options.nextButton);
	},
	
	
	createTabs: function()
	{
		this.dts.invoke('hide');

		this.tabMenu = new Element('div', {'class' : 'noprint'});
		var tabMenuUl = new Element('ul', {'class' : 'tabnav'});

		for (var i=0; i<this.count; i++)
		{
			this.dls[i].hide();

			tabMenuUlLi = new Element('li').update(new Element('a', {rel: i, id: this.ids[i] + this.id}).update(this.dts[i].innerHTML));
			tabMenuUl.insert(tabMenuUlLi);
		}
		
		this.tabMenu.insert(tabMenuUl);
		this.dl.insert({Before: this.tabMenu});

		tabMenuUl.select('a').each(function(element){
			element.observe('click', function(){
				this.show(element.rel);
			}.bindAsEventListener(this, element));
		}.bind(this));

		if (this.prevButton)
		{
			this.prevButton.observe('click', function(){
				this.show(--this.index);
			}.bindAsEventListener(this));
		}
		
		if (this.nextButton)
		{
			this.nextButton.observe('click', function(){
				this.show(++this.index);
			}.bindAsEventListener(this));
		}
	},
	
	
	show: function(index)
	{
		this.index = index;
		
		for (var i=0; i<this.count; i++)
			if (this.ids[i] == index)
				this.index = i;
		
		this.tabMenu.select('li.on').each(function(element){
			element.removeClassName('on');
		});
		this.tabMenu.select('li')[this.index].addClassName('on');

		for (var i=0; i<this.count; i++)
		{
			if (i == this.index)
				this.dts[i].next().show();
			else
				this.dts[i].next().hide();
		}
		
		if (this.prevButton)
		{
			if (this.index == 0)
			{
				this.prevButton.addClassName('disabled');
				this.prevButton.disable();
			}
			else
			{
				this.prevButton.removeClassName('disabled');
				this.prevButton.enable();
			}
		}

		if (this.nextButton)
		{
			if (this.index == this.count-1)
			{
				this.nextButton.addClassName('disabled');
				this.nextButton.disable();
			}
			else
			{
				this.nextButton.removeClassName('disabled');
				this.nextButton.enable();
			}
		}
	},
	
	addTabFunction: function(tabId, func) {

		if ($(tabId + this.id))
		{
			$(tabId + this.id).observe('click', func);
		}
	}

});




var ExclusiveCheckboxControl = Class.create({

	initialize: function(fields) 
	{
		var checkboxes = new Array();
		
		for (var i=0; i<fields.length; i++)
		{
			if (field = $(fields[i]))
				checkboxes.push(field);
		}

		for (var i=0; i<checkboxes.length; i++)
		{
			checkboxes[i].observe('click', function(){
				if (this.checked)
				{
					for (var j=0; j<checkboxes.length; j++)
					{
						if (this != checkboxes[j] && checkboxes[j].checked)
							checkboxes[j].checked = false;
					}
				}
			});
		}
	}

});





var VisibilityToggler = Class.create({

	options: {
		onClick: Prototype.emptyFunction,
		showText: '',
		hideText: '',
		css: true
	},

	initialize: function(linkId, layerId, options) 
	{
		Object.extend(this.options, options || {});

		this.link = $(linkId);
		if (!this.link)
			return;
		if (Object.isArray(layerId))
			this.layer = layerId;
		else
			this.layer = $(layerId);
		this.showText = (this.options.showText) ? this.options.showText : this.link.innerHTML;
		this.hideText = (this.options.hideText) ? this.options.hideText : this.link.innerHTML;
		if (Object.isArray(this.layer))
			this.visible = false;
		else
			this.visible = this.layer.visible();
		
		if (this.visible)
		{
			this.link.update(this.hideText);
			if (this.options.css)
				this.link.addClassName('visibilityToggler visible');
		}
		else
		{
			this.link.update(this.showText);
			if (this.options.css)
				this.link.addClassName('visibilityToggler hidden');
		}
		
		this.link.observe('click', this.toggle.bindAsEventListener(this));
	},
	
	toggle: function(ev)
	{
		ev.stop();
		
		if (this.visible)
			this.hide();
		else
			this.show();
		
		this.options.onClick.bind(this)();
	},
	
	show: function() {
		if (Object.isArray(this.layer))
			this.layer.invoke('show');
		else
			this.layer.show();

		this.link.update(this.hideText);
		if (this.options.css)
		{
			this.link.addClassName('visibilityToggler visible');
			this.link.removeClassName('visibilityToggler hidden');
		}
		this.visible = !this.visible;
	},

	hide: function() {
		if (Object.isArray(this.layer))
			this.layer.invoke('hide');
		else
			this.layer.hide();

		this.link.update(this.showText);
		if (this.options.css)
		{
			this.link.removeClassName('visibilityToggler visible');
			this.link.addClassName('visibilityToggler hidden');
		}
		this.visible = !this.visible;
	}

});




var Overlay = Class.create({

	initialize: function(color, opacity) 
	{
		this.zIndex = 3000;

		this.overlay = new Element('div');
		var opacityMoz = opacity / 100;
		this.overlay.setStyle({
			zoom: 1,
			position: 'absolute',
			left: '0px',
			top: '0px', 
			width: '100%',
			height: this.getPageSize()[1] + 'px',
			opacity: opacityMoz,
			backgroundColor: color,
			zIndex: this.zIndex
		});
		document.body.insert(this.overlay);
	},
	
	
	getZindex: function() {
		return this.zIndex;
	},
	
	
	remove: function() {
		this.overlay.remove();
	},

		
	getPageSize: function() {

		var xScroll, yScroll;
		
		if (window.innerHeight && window.scrollMaxY) {	
			xScroll = document.body.scrollWidth;
			yScroll = window.innerHeight + window.scrollMaxY;
		} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
			xScroll = document.body.scrollWidth;
			yScroll = document.body.scrollHeight;
		} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
			xScroll = document.body.offsetWidth;
			yScroll = document.body.offsetHeight;
		}
		
		var windowWidth, windowHeight;
		if (self.innerHeight) {	// all except Explorer
			windowWidth = self.innerWidth;
			windowHeight = self.innerHeight;
		} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
			windowWidth = document.documentElement.clientWidth;
			windowHeight = document.documentElement.clientHeight;
		} else if (document.body) { // other Explorers
			windowWidth = document.body.clientWidth;
			windowHeight = document.body.clientHeight;
		}	
		
		// for small pages with total height less then height of the viewport
		if(yScroll < windowHeight){
			pageHeight = windowHeight;
		} else { 
			pageHeight = yScroll;
		}
	
		// for small pages with total width less then width of the viewport
		if(xScroll < windowWidth){	
			pageWidth = windowWidth;
		} else {
			pageWidth = xScroll;
		}
	
	
		arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
		return arrayPageSize;
	}

});


var CheckboxToggler = Class.create({

	initialize: function(inputId, divId, func) {
		this.input = $(inputId);
		if (!this.input)
			return false;
		
		var div = $(divId);

		if (!this.input.checked)
			div.hide();

		if (!func)
			func = function() {};
		func = func.bind(this);

		this.input.observe('click', function(){
			if (this.checked)
				div.show();
			else
				div.hide();
			func();
		});
	}

});





function setcookie(name, value, expires, path, domain, secure) 
{
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime(today.getTime());

	// if the expires variable is set, make the correct 
	// expires time, the current script below will set 
	// it for x number of days, to make it for hours, 
	// delete * 24, for minutes, delete * 60 * 24
	if (expires)
	{
		expires = expires * 1000 * 60;
	}
	var expires_date = new Date(today.getTime() + (expires) );

	document.cookie = name + "=" +escape( value ) +
	( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + 
	( ( path ) ? ";path=" + path : "" ) + 
	( ( domain ) ? ";domain=" + domain : "" ) +
	( ( secure ) ? ";secure" : "" );
}


function getcookie(name) 
{
	var start = document.cookie.indexOf(name + "=");
	var len = start + name.length + 1;
	if ((!start) && (name != document.cookie.substring(0, name.length)))
	{
		return null;
	}
	if (start == -1) return null;
	var end = document.cookie.indexOf(";", len);
	if (end == -1) end = document.cookie.length;
	return unescape( document.cookie.substring(len, end));
}



function deletecookie(name, path, domain) 
{
	if (getcookie(name)) 
		document.cookie = name + "=" + ((path) ? ";path=" + path : "") + ((domain) ? ";domain=" + domain : "" ) + ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}


var TableOfContents = Class.create({

	initialize: function(divId, labelClass) {
		var div = $(divId);

		div.update();
		var labels = $$('.' + labelClass);
		for (i=labels.length-1; i>=0; i--)
		{
			var item = labels[i];

			if (item.up().visible())
			{
				a = new Element('a', {}).update(item.innerHTML);
				a.observe('click', function(){
					this.scrollTo();
				}.bind(item));
				div.insert({Top: new Element('li').update(a)});
			}
		}
	}

});


var FormElementObserver = Class.create({

	initialize: function(elements, events, func) {
		if (typeof elements == 'string')
			elements = [elements];

		if (typeof events == 'string')
			events = [events];
	
		for (var i=0; i<elements.length; i++)
			for (var j=0; j<events.length; j++)
				if ($(elements[i]))
					$(elements[i]).observe(events[j], func);
	}

});


fieldsetMethods = {

	toggleDisabled: function(element) {
		if (typeof fieldsetData == 'undefined')
			fieldsetData = new Array();
		
		element.toggleClassName('disabled');
		element.select('input').each(function(element){
			element.disabled = !element.disabled;
//			element.toggleClassName('disabled');
		});
	},

	disable: function(element) {
		element.addClassName('disabled');
		element.select('input').each(function(element){
			element.disabled = true;
//			element.addClassName('disabled');
		});
	},

	enable: function(element) {
		element.removeClassName('disabled');
		element.select('input').each(function(element){
			element.disabled = false;
//			element.removeClassName('disabled');
		});
	},

	reset: function(element) {
		element.select('input[type="text"], select, textarea').each(function(element){
			element.value = '';
		});
	}

};
Element.addMethods('FIELDSET', fieldsetMethods);




var FileUploadField = Class.create({

	id: null,
	uploadField: null,
	afterUpload: null,
	loadingMessage: null,
	response: null,
	errorMessage: null,
	container: null,
	iframe: null,
	form: null,
	originalFormAction: null,
	originalFormTarget: null,
	hidden: null,
	changeCallback: Prototype.emptyFunction,
	tmpfield: null,

	initialize: function(elementId, afterUpload) {
		this.uploadField = $(elementId);
		this.id = this.uploadField.id;

		this.container = this.uploadField.wrap('div', {id: this.uploadField.id + '-wrap'});
		this.afterUpload = afterUpload || Prototype.emptyFunction;
		this.loadingMessage = new Element('div').setStyle({marginTop: '5px', display: 'none'}).update('Kis türelmet, feltöltés folyamatban...');
		this.loadingMessage.addClassName('FileUploadFieldLoadingMessage');
		this.container.insert(this.loadingMessage);
		this.response = new Element('div').setStyle({marginTop: '5px', display: 'none'});
		this.response.addClassName('FileUploadFieldResponseMessage');
		this.container.insert(this.response);
		this.errorMessage = new Element('div').setStyle({marginTop: '5px', display: 'none'});
		this.container.insert(this.errorMessage);
		this.form = this.uploadField.up('form');
		this.originalFormAction = this.form.getAttribute('action') || location.href;
		this.originalFormTarget = this.form.getAttribute('target') || 'self';

		if (this.form.select('.__tmphiddenfield__').length == 0)
		{
			this.tmpfield = new Element('input', {
				type: 'hidden', 
				name: '__tmphiddenfield__', 
				'class': '__tmphiddenfield__'
			});
			this.form.insert(new Element('div').update(this.tmpfield));
		}
		else
			this.tmpfield = this.form.select('.__tmphiddenfield__')[0];
	},
	
	startObserving: function(callback) {
		this.changeCallback = callback;
		this.uploadField.observe('change', function(){
			this.changeCallback.bind(this)();
		}.bindAsEventListener(this));
	},

	stopObserving: function(eventName) {
		this.uploadField.stopObserving(eventName);
	},
	
	disable: function() {
		this.uploadField.disable();
	},

	enable: function() {
		this.uploadField.enable();
	},
	
	showLoadingMessage: function() {
		this.loadingMessage.show();
	},

	hideLoadingMessage: function() {
		this.loadingMessage.hide();
	},
	
	upload: function() {
		this.response.hide();
		var iframeId = 'iframe_' + this.id;
		this.tmpfield.value = this.id;
		this.iframe = new Element('iframe', {id: iframeId, name: iframeId});
		this.iframe.setStyle({display: 'none', height: 0, width: 0});
		this.loadingMessage.insert({Before: this.iframe});

		this.form.setAttribute('action', '/upload');
		this.form.setAttribute('target', iframeId);
		this.form.submit();
		
		this.form.setAttribute('action', this.originalFormAction);
		this.form.setAttribute('target', this.originalFormTarget);
	},
	
	setResponse: function(response) {
		this.iframe.remove();
		if (response.success)
		{
			this.response.update('Feltöltve: ' + response.originalname + ' - ' + response.size + ' - ');
			this.response.insert(a = new Element('a').update('Mégse'));
			if (this.uploadField.id.match(/[\w]+\[[\w]+\]/))
			{
				parts = this.uploadField.id.split('[');
				name = parts[0] + '[upload_' + parts[1];
			}
			else
				name = 'upload_' + this.uploadField.id;
			this.response.insert(new Element('input', {
				type: 'hidden',
				name: name, 
				value: response.basename
			}));
			a.observe('click', function(){
				this.reset();
			}.bindAsEventListener(this));
			this.response.show();
		}
	},
	
	reset: function() {
		var newUploadField = new Element('input', {
			type: 'file',
			id: this.uploadField.id,
			name: this.uploadField.name
		});
		this.stopObserving();
		this.uploadField.remove();
		this.uploadField = newUploadField;
		this.container.insert({Top: this.uploadField});
		this.startObserving(this.changeCallback);

		this.response.hide();
	}
	
});


if (!window.UploadManager)
	var UploadManager = new Object();

UploadManager.Methods = {

	fields: new Array(),
	uploadInProgress: false,
	activeField: null,

	observe: function(elementId, afterUpload) {
		try {
			var field = new FileUploadField(elementId, afterUpload);
		}
		catch (e)
		{
			return false;
		}

		field.startObserving(function(){
			UploadManager.addToList(this);
		})
		
		return field;
	},
	
	addToList: function(field) {
		UploadManager.fields.push(field);
		field.disable();
		UploadManager.iterate();
	},

	iterate: function() {
		if (UploadManager.uploadInProgress)
			return;
		else
		{
			if (UploadManager.activeField = UploadManager.fields.shift())
				UploadManager.submit();
		}
	},

	submit: function() {
		field = UploadManager.activeField;
		field.enable();
		UploadManager.uploadInProgress = true;
		field.showLoadingMessage();
		field.upload();
	},
	
	processResponse: function(response) {
		field = UploadManager.activeField;
		field.hideLoadingMessage();
		field.setResponse(response);

		field.afterUpload();

		UploadManager.uploadInProgress = false;
		UploadManager.iterate();
	}
}

Object.extend(UploadManager, UploadManager.Methods);




var CheckboxController = Class.create({

	initialize: function(id, allSelectorValue) {
		var container = $(id);
		var allSelector = container.select('input[value="' + allSelectorValue + '"]')[0];
		var allInputs = container.select('input');
		var otherInputs = container.select('input:not([value="' + allSelectorValue + '"])');
		
		allSelector.observe('click', function(){

			if (this.checked)
				otherInputs.each(function(element){
					element.checked = false;
				});
		});

		otherInputs.each(function(element){
			element.observe('click', function(){
				allSelector.checked = false;
			});
		});

	}

});

