var Cms = {
	pageRID: null,
	modules: $H(),
	cookies: null,
	
	init: function(pageRID) {
		this.pageRID = pageRID;
		this.initFavorites();
		//this.initTinyMCE();
		if ( $('cms-panel')!==null ) {
			document.body.style.paddingTop = $('cms-panel').getHeight() + 'px';
		}
	},
	
	registerModule: function(module) {
		if ( !(module instanceof Cms.Module) ) {
			module = new Cms.Module(module);
		}
		this.modules.set(module.id, module);
		return module;
	},
	
	_hSelects: $H(),
	initHierSelect: function (element, childData, selected) {
		element.onchange = null;
		element.multiple = null;
		var id = element.identify();
		var hSel = new Cms.HierSelect(element, childData, selected);
		this._hSelects.set(id, hSel);
		hSel.onChange();
	},

	initFavorites: function () {
		if ( null === $('favorites-add') ) return;
	
		this.cookies = new CookieJar({
			expires:3600*24*90,   // seconds
			path: '/'
		});
		var fav = this.cookies.get('favorites');
		
		if ( (fav !== null) && (-1 !== fav.indexOf(this.pageRID)) ) {
			$('favorites-add').hide();
			$('favorites-remove').show();
		} 
		else {
			$('favorites-add').show();
			$('favorites-remove').hide();
		}
		
		$('favorites-add').observe('click', function(e) {
			$('favorites-add').toggle();
			$('favorites-remove').toggle();
			var fav = this.cookies.get('favorites');
			if ( !Object.isArray(fav) ) {
				fav = new Array();
			}
			fav.push(this.pageRID);
			this.cookies.put('favorites', fav);
			Event.stop(e);
		}.bind(this));
		$('favorites-remove').observe('click', function(e) {
			$('favorites-add').toggle();
			$('favorites-remove').toggle();
			this.cookies.put('favorites', this.cookies.get('favorites').without(this.pageRID));
			Event.stop(e);
		}.bind(this));
	},
	
	ajaxAction: function (url, options) {
		options = Object.extend({
			onComplete: this.handleAJAXComplete.bind(this)
			//onFailure: this.handleAJAXFailure.bind(this)
		}, options);
		new Ajax.Request(url, options);	
	},
	handleAJAXComplete: function (transport, ipe) {
		alert(transport.responseJSON.message);
		if ( transport.responseJSON.redirect ) {
			window.location.href = transport.responseJSON.redirect; 
		}
	},
	handleAJAXFailure: function (transport, ipe) {
	},
	
	highlightEditable: function () {
		Cms.message('Kliknij pole które chcesz edytować');
		$$('form.inplaceform').each(function (element){
			new Effect.Highlight(element, {startcolor: '#e7efd6', duration: 3, restorecolor: 'transparent'});
			
			//new Effect.Pulsate(element);
			
		});
	},
	
	message: function (message) {
		$('cms-panel-message').show();
		$('cms-panel-message').update(message);
		new Effect.Fade('cms-panel-message', {delay: 5});
	}
}; 

Cms.Module = Class.create({
	id: null,
	moduleId: null,
	content: null,
	inplaceForm : null,
	forms: $H(),
	options: {},
	ajaxFormId: null,
	
	initialize: function (id, options) {
		this.id = id;
		this.content = $(id);
		
		var parts = id.split('-');
		this.moduleId = parts[parts.length-1];
		
		this.options = Object.extend(Cms.Module.DefaultOptions, options);
	},
	
	registerInPlaceForm: function () {
		this.inplaceForm = new Cms.InPlaceForm($(this.id));
	},

	registerForm: function (formId, options) {
		options = Object.extend({
				ajax: { 
					onCreate: this.AJAXonCreate.bind(this),
					onComplete: this.AJAXonComplete.bind(this),
					onFailure: this.AJAXonFailure.bind(this)
				},
				htmlResponse: true,
				success: this.content
			}, options)
		this.forms.set(formId, new Cms.ModalForm(formId, options) );
	},
	
	registerAjaxForm: function(form) {
		form = $(form);
		this.ajaxFormId = form.id;
		form.observe('submit', function (e) {
			new Ajax.Updater(this.content, form.action, {
				parameters: form.serialize(),
				onCreate: this.AJAXonCreate.bind(this),
				onComplete: this.refreshAjaxForm.bind(this)
			});
			Event.stop(e);
		}.bind(this));
	},
	
	refreshAjaxForm: function() {
		this.AJAXonComplete();
		this.registerAjaxForm(this.ajaxFormId);
	},
	
	openForm: function (formId) {
		if ( this.forms.get(formId) ) {
			this.forms.get(formId).open();
		}
		else {
			alert('error');
		}
	},
	
	url: function (action, controller) {
		return '/module/' + controller + '/' + action + '/id/' + this.moduleId + '/pageRID/' + Cms.pageRID;
	},
	
	showSaving: function() {
		this.content.addClassName(this.options.savingClassName);
	},
	
	hideSaving: function() {
		this.content.removeClassName(this.options.savingClassName);
	},
	
	AJAXonCreate: function () {
		this.showSaving();
	},
	
	AJAXonComplete: function () {
		this.hideSaving();
	},
	
	AJAXonFailure: function (transport) {
		message = '';
		$H(transport.responseJSON.errors).each(function (pair) {
			$H(pair.value).each(function (pair2) {
				message += pair2.value + "\r\n";
			});
		});
		alert(message);
	}

});

Cms.Module.DefaultOptions = {
	savingClassName: 'cms-module-saving'
	//controller: 'cms-module',
	//action: 'index' 
};


Cms.Module.Gallery = Class.create(Cms.Module, {
	initialize: function ($super, id, options) {
		$super(id, options);
		this.options = Object.extend(Cms.Module.Gallery.DefaultOptions, this.options);
	},
	
	attachActionDelete: function() {
		$$('#'+this.id+' a[rel]').each(function (item) {
			//item.relativize();
			item.style.position = 'relative';
			var btn = new Element(this.options.deleteBtnTag, {
				className: this.options.deleteBtnClass,
				title: this.options.deleteBtnTitle
			});
			btn.observe('click', function (e) {
				if ( confirm(this.options.deleteConfirmationText) ) {
					new Ajax.Updater(this.content, this.url('deleteimage', 'gallery'), {
						parameters: { file: e.element().parentNode.href },
						onComplete: this.AJAXonComplete.bind(this),
						onCreate: this.AJAXonCreate.bind(this)
					});
				}
				
				Event.stop(e)
			}.bind(this));
				
			item.insert( btn );
		}.bind(this));
	},
	
	AJAXonComplete: function () {
		this.attachActionDelete();
		this.hideSaving();
	}
});

Cms.Module.Gallery.DefaultOptions = {
	deleteBtnTag: 'span',
	deleteBtnClass: 'gallery-delete-btn',
	deleteBtnTitle: 'usuń zdjęcie',
	deleteConfirmationText: 'Czy na pewno chcesz usuąć to zdjęcie?' 
};

Cms.HierSelect = Class.create({
	element: null,
	childSelect: null,
	childData: null,
	initSelected: $A(),
	initialize: function (element, childData, selected) {
		this.element = element;
		this.childData = childData;
		this.id = this.element.identify(); 
		//alert($F(this.element));
		
		if ( selected !== null ) {
			this.initSelected = selected;
		} 
		
		if ( this.initSelected.length > 0 ) {
			var value = this.initSelected.shift(); 
			var options = element.childElements();
			for (var i=0; i<options.length; i++) {
				options[i].selected = options[i].value == value ? 'selected' : '';  
			}
		}  
		
		this.element.observe('change', this.onChange.bind(this));
	},
	
	onChange: function (e) {
		if ( this.childSelect ) {
			this.childSelect.destroy();
			delete this.childSelect;
		}

		var value = this.childData[this.element.value];
		if( typeof(value) == 'object' ) {

			var select = document.createElement('select');
			select.setAttribute('name', this.element.name);
			
			//var select = new Element('select', {name: this.element.name});
			
			//var initValue = this.initSelected.length > 0 ? this.initSelected.shift() : null;
			//var initValue = this.initSelected.shift();
			var found = false;
			
			$H(value.children).each(function (pair) {
				//alert(pair);
				var text = typeof(pair.value) == 'object' ? pair.value.title : pair.value;
				var opt = new Element('option', {value: pair.key});
				//if (value && (pair.key == initValue)) {
				//	found = true;
				//	opt.selected = 'selected';
				//}
				opt.update(text);

				select.insert(opt);
			});
			this.element.insert({after: select});
			
			this.childSelect = new Cms.HierSelect(select, value.children, this.initSelected);
			
			//if (found)
				this.childSelect.onChange();
		}
		
		//Event.stop(e);
	},
	
	destroy: function () {
		if ( this.childSelect ) {
			this.childSelect.destroy();
			delete this.childSelect;
		}
		Element.remove(this.element);
		delete this.element;
		return this; 
	}
});
 
 
Cms.config = { 
	TinyMCE: {
		simple: {
			language: "pl",
			mode : "none",
			theme : "simple",
			content_css : "css/theme.css",
			entity_encoding : "raw",
			plugins: "paste"
//			invalid_elements : "style" 
		},
		advanced: {
			language: "pl",
			mode : "none",
			theme : "advanced",
			content_css : "css/theme.css",
			entity_encoding : "raw"
		}
	}
}; 

Element.addMethods('TEXTAREA', {
	startTinyMCE: function (element, theme) {
		if ( theme === null ) theme = 'simple'; 
		//if ( Cms.tinyMCE.configs[theme] ) {
		$w(element.className).each(function (classname){
			//alert(classname.substring(3));
			if( classname.startsWith('mce') ) tinyMCE.init(Cms.config.TinyMCE[classname.toLowerCase().substring(3)]);;
		});
		
		tinyMCE.execCommand('mceAddControl', false, element.id);
		//} 
	},
	stopTinyMCE: function (element) {
		tinyMCE.execCommand('mceRemoveControl', false, element.id);
	}
});

