
var DropDown = Class.create({
	dl: null,
	dt: null,
	dd: null,
	bel: null, // boundEventListener
	visible: false,

	initialize: function(element) 
	{
		if (!Object.isElement($(element)))
			return;
		
		this.dl = $(element);
		this.dt = this.dl.select('dt')[0].select('a')[0];
		this.dd = this.dl.select('dd')[0];

		this.bel = function(e){
			if (e.element() == this.dt)
				return;
			this.dt.up().removeClassName('on');
			this.dd.fade({duration: 0.2, afterFinish: function(){
				this.dl.removeClassName('on');
			}.bind(this)});
			document.stopObserving('click', this.bel);
			this.visible = false;
		}.bindAsEventListener(this)

		this.dt.observe('click', function(ev){
			if (this.visible)
				return false;
			this.visible = true;
			this.dd.hide();
			this.dl.addClassName('on');
			this.dt.up().addClassName('on');
			this.dd.appear({duration: 0.2});
			document.observe('click', this.bel);
		}.bindAsEventListener(this));
	}

});



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;
			});
		});

	}

});



var InputDefaultValue = Class.create({

	initialize: function(fieldId, defaultValue) 
	{
		field = $(fieldId);
		if (!field)
			return false;

		field.observe('blur', function(){
			if (!$F(this))
				this.value = defaultValue;
		});

		field.observe('focus', function(){
			if ($F(this) == defaultValue)
				this.value = '';
		});

		if (!$F(field))
			field.value = defaultValue;
	}

});




var TabMenuFromDL = Class.create({

	initialize: function(fieldId, options)
	{
		this.id = Math.round(100000 * Math.random());
		
		this.dl = $(fieldId);
		var children = this.dl.childElements();

		this.ids = new Array();
		this.dts = new Array();
		this.dds = new Array()

		for (var i=0; i<children.length; i++)
		{
			switch (children[i].tagName)
			{
				case 'DT':
					this.dts.push(children[i]);
					this.ids.push(children[i].next().id);
					break;
				case 'DD':
					this.dds.push(children[i]);
					break;
			}
		}

		this.count = this.dts.length;

		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');
		this.tabMenu.addClassName('noprint');
		var tabMenuUl = new Element('ul');
		tabMenuUl.addClassName('tabnav');

		for (var i=0; i<this.count; i++)
		{
			this.dds[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, invert) {
		this.input = $(inputId);
		if (!this.input)
			return false;
		
		var div = $(divId);

		if (!this.input.checked)
		{
			if (invert)
				div.show();
			else
				div.hide();
		}

		if (!func)
			func = function() {};
		func = func.bind(this);

		this.input.observe('click', function(){
			if (invert)
			{
				if (this.checked)
					div.hide();
				else
					div.show();
			}
			else
			{
				if (this.checked)
					div.show();
				else
					div.hide();
			}
			func();
		});
	}

});


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.php');
		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);




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";
}


textareaMethods = {

	convertToFCK: function(element, options)
	{
		
		options = options || {};
		if (!options.ToolbarSet)
			options.ToolbarSet = 'Default';
		if (!options.Height)
			options.Height = element.getHeight();
		
		var oFCKeditor = new FCKeditor(element.id) ;
		oFCKeditor.BasePath	= '/_includes/FCKeditor/';
		oFCKeditor.Height = options.Height;
		oFCKeditor.ToolbarSet = 'PartnerOldal';
		oFCKeditor.Config["GoogleMaps_Key"] = GoogleMapAPIKey;
		oFCKeditor.ReplaceTextarea() ;
	}
}
	
Element.addMethods('TEXTAREA', textareaMethods);


var PopupWindow = Class.create({
	
	defaultOptions: {
		centered: true,
		width: 750,
		height: 600,
		modal: true,
		toolbar: false,
		location: true,
		directories: false,
		hotkeys: false,
		status: false,
		menubar: false,
		scrollbars: true,
		resizable: true,
		copyhistory: false,
		modal: true,
		left: 100,
		top: 20,
		maxheight: false,
		padding: 30
	},

	initialize: function(href, options) {
		Object.extend(this.defaultOptions, options || {});
		
		var props = '';
		props += 'toolbar=' + ((this.defaultOptions.toolbar) ? 'yes' : 'no');
		props += ',';
		props += 'location=' + ((this.defaultOptions.location) ? 'yes' : 'no');
		props += ',';
		props += 'directories=' + ((this.defaultOptions.directories) ? 'yes' : 'no');
		props += ',';
		props += 'hotkeys=' + ((this.defaultOptions.hotkeys) ? 'yes' : 'no');
		props += ',';
		props += 'status=' + ((this.defaultOptions.status) ? 'yes' : 'no');
		props += ',';
		props += 'menubar=' + ((this.defaultOptions.menubar) ? 'yes' : 'no');
		props += ',';
		props += 'scrollbars=' + ((this.defaultOptions.scrollbars) ? 'yes' : 'no');
		props += ',';
		props += 'resizable=' + ((this.defaultOptions.resizable) ? 'yes' : 'no');
		props += ',';
		props += 'copyhistory=' + ((this.defaultOptions.copyhistory) ? 'yes' : 'no');
		props += ',';
		props += 'modal=' + ((this.defaultOptions.modal) ? 'yes' : 'no');
		props += ',';
		props += 'width=' + this.defaultOptions.width;
		props += ',';
		props += 'height=' + this.defaultOptions.height;

		var width = this.defaultOptions.width;
		var height = this.defaultOptions.height;

		if (this.defaultOptions.maxheight)
			height = screen.height - 2 * this.defaultOptions.padding - 50;

		if (this.defaultOptions.centered)
		{
			var left = Math.round((screen.width - width) / 2);
			var top = Math.round((screen.height - height - 25) / 2);
		}
		else
		{
			var left = this.defaultOptions.left;
			var top = this.defaultOptions.top;
		}

		props += ',';
		props += 'left=' + left;
		props += ',';
		props += 'top=' + top;
		this.win = window.open(href, 'ujablak', props);
		this.win.focus();
	}

});
