/**
 * THIS	SCRIPT BASED ON " STYLING FILE INPUTS 1.0 created by Shaun Inman <http://www.shauninman.com/> | 2007-09-07 "
 * 
 * CREATED BY CSABA GYENGE
 * CREATED AT 2009-11-17
 */

if (!window.Villam) {
	var Villam = {};
};

/**
 * Villam.Util
 */
if (!window.Villam.Util) {
	Villam.Util = {};
};

Villam.Util.URI = {
	getFilename : function(filename){
		return filename.replace(/^.*[\\\/]/, '');
	}
};


/**
 * Villam.Forms
 */
if (!window.Villam.Forms) {
	Villam.Forms = {};
};

/**
 * Villam.Forms.File
 */
Villam.Forms.File = {
	fileClass				: 'villam-form-file-input',
	wrapClass				: 'villam-form-file',
	displayClass			: 'villam-form-file-display',
	
	fini : false,
	able : false,
	init : function()
	{
		this.fini = true;
		
		var ie = 0 //@cc_on + @_jscript_version
		if (window.opera || (ie && ie < 5.5) || !document.getElementsByTagName) { return; } // no support for opacity or the DOM
		this.able = true;
	},
	
	stylize : function(elem)
	{
		if (!this.fini) { this.init(); };
		if (!this.able) { return; };
		elem.parentNode.file = elem;
		var originalPosition = $(elem.parentNode.file).getPosition($(elem.parentNode));
		elem.parentNode.file.originalTop = originalPosition.y;
		elem.parentNode.file.originalLeft = originalPosition.x;
		elem.parentNode.file.coords = $(elem.parentNode.file).getCoordinates();
		elem.parentNode.file.display = $(elem.parentNode).getElement("." + this.displayClass);
		elem.parentNode.file.onchange = elem.parentNode.file.onmouseout = function(){
			if (this.value) {
				this.display.value = Villam.Util.URI.getFilename(this.value);
			}
			this.display.focus();
		};
		elem.parentNode.onmousemove = function(e) {
			if (typeof e == 'undefined') e = window.event;
			if (typeof e.pageY == 'undefined' &&  typeof e.clientX == 'number' && document.documentElement)
			{
				e.pageX = e.clientX + document.documentElement.scrollLeft;
				e.pageY = e.clientY + document.documentElement.scrollTop;
			};

			var containerCoords = this.getCoordinates();
			var x = e.pageX - containerCoords.left;
			var y = e.pageY - containerCoords.top;
			var w = this.file.coords.width;
			var h = this.file.coords.height;

			if (x < 0 || containerCoords.width < x || y < 0 || containerCoords.height < y){
				this.file.disabled = true;
				return;
			}
			this.file.disabled = false;

			this.file.setStyles({
				'top' : y - (h / 2) - this.file.originalTop,
				'left' : x - (w - 30) - this.file.originalLeft
			});
		};
	},
	
	stylizeById : function(id)
	{
		this.stylize(document.getElementById(id));
	},
	
	stylizeAll : function()
	{
		if (!this.fini) { this.init(); };
		if (!this.able) { return; };
		
		var inputs = document.getElementsByTagName('input');
		for (var i = 0; i < inputs.length; i++)
		{
			var input = inputs[i];
			if (input.type == 'file' && input.className.indexOf(this.fileClass) != -1 && input.parentNode.className.indexOf(this.wrapClass) != -1)
			{	
				this.stylize(input);
			};
		};
	}
};
/*
window.addEvent('domready' , function(){
	Villam.Forms.File.stylizeAll();
});
*/
/**
 * Villam.Forms.CheckboxGroup
 */
var CheckboxGroup = new Class({
	Implements : Options,

	ul : null,

	options : {
		
	},

	cbOnChange : [],
	
	requiredGroups : [],
	
	initialize: function(ul , options){
		this.ul = ul;
		this.setOptions(options);
		this.stylize();
	},
	
	getChecked : function(){
		var checked = [];
		this.ul.getElements('li').each(function(li){
			if (li.relatedInput.get('value').toInt()){
				checked.push(li.relatedInput.get('value').toInt());
			}
		});
		return checked;
	},
	
	getItem : function(inputName){
		this.ul.getElements('li').each(function(li){
			if (li.relatedInput.get('name') == inputName){
				liInput = li;
			}
		});
		return liInput;
	},
	
	isChecked : function( itemProperty ){
		itemValue = 0;
		this.ul.getElements('li').each(function(li){
			if (li.relatedInput.get('name') == itemProperty){
				itemValue = li.relatedInput.get('value').toInt();
				return;
			}
		});
		return itemValue;
	},
	
	toggleItem : function(li){
		if (li.hasClass('checked')) {
			if ($defined(li.requiredGroup)){
				i = 0;
				this.requiredGroups[li.requiredGroup].each(function(e){
					if (e.hasClass('checked')) i++;
				});
				if (i <= 1) return -1;
			}
			li.removeClass('checked');
			li.relatedInput.setProperty('value' , 0);
			value = 0;
		} else {
			li.addClass('checked');
			li.relatedInput.setProperty('value' , 1);
			value = 1;
		}		
		return value;
	},

	stylize: function (){
		this.ul.getElements('li').each(function(li){
			// handle required groups
			requiredGroup = li.getElement('input.required-group');
			if ($chk(requiredGroup)) {
				li.requiredGroup = requiredGroup.get('value');
				li.requiredGroupAlert = requiredGroup.get('title');
				if (!$defined(this.requiredGroups[li.requiredGroup])) {
					this.requiredGroups[li.requiredGroup] = [];
				}
				this.requiredGroups[requiredGroup.value].push(li);
				requiredGroup.dispose();
			}
			// handle value
			li.relatedInput = li.getElement('input');
			if (li.relatedInput.value == 1){
				li.addClass('checked');
			} else {
				li.removeClass('checked');
			}
			li.addEvent('click' , function(){
				value = this.toggleItem(li);
				this.cbOnChange.each(function(callback){
					callback.run([this , li , value ]);
				}.bind(this));
			}.bind(this));
		}.bind(this));
	},
	
	addOnChangeCallback: function(callback){
		this.cbOnChange.push(callback);
	}	
});

/**
 * Villam.Forms.RadiobuttonGroup
 */
var RadiobuttonGroup = new Class({
	Implements : Options,

	ul : null,
	
	relatedInput : null,

	options : {
		
	},

	cbOnChange : [],
	
	initialize: function(ul , options){
		this.ul = ul;
		this.relatedInput = this.ul.getElement('input');
		this.setOptions(options);
		this.stylize();
	},
	
	getRadioItem : function(value){
		res = null;
		this.ul.getElements('li').each(function(li){
			if (li.relatedValue == value){
				res = li;
				return;
			}
		});
		return res;
	},
	
	getSelectedValue : function(){
		return this.relatedInput.get('value');
	},
	
	setSelectedValue : function(value){
		radioitem = this.getRadioItem(value);
		if (!$chk(radioitem)) return 0;
		this._checkItem(radioitem);
	},
	
	_checkItem : function(li){
		li.addClass('checked');
		this.relatedInput.setProperty('value' , li.relatedValue);
		return 1;
	},
		
	_uncheckAll : function(){
		this.ul.getElements('li').each(function(li){
			li.removeClass('checked');
		}.bind(this));
	},

	stylize: function (){
		this.ul.getElements('li').each(function(li){
			li.relatedValue = li.get('title');
			li.removeProperty('title');
			// handle value
			if (this.relatedInput.value == li.relatedValue){
				this._checkItem(li);
			} else {
				li.removeClass('checked');
			}
			li.addEvent('click' , function(){
				if (this.relatedInput.value == li.relatedValue) return true;
				this._uncheckAll();
				this._checkItem(li);
				this.cbOnChange.each(function(callback){
					callback.run([this , li , li.relatedValue ]);
				}.bind(this));
			}.bind(this));
		}.bind(this));
	},

	addOnChangeCallback: function(callback){
		this.cbOnChange.push(callback);
	}	
});

/**
 * Villam.Forms.Button
 */
Villam.Forms.Button = {
	buttonSelector : '.villam-form-button',
	buttonSelectorClass : 'villam-form-button',

	stylizeAll: function (){
		$(document).getElements(this.buttonSelector).each(function(button){
			// get button classname
			var classes = button.get('class');
			classes = classes.split(' ');
			classes.each(function(className){
				if (className != this.buttonSelectorClass && className.contains(this.buttonSelectorClass)) {
					button.buttonClassName = className;
				}
			}.bind(this));
			// add event
			button.addEvent('mouseover' , function(event){
				this.removeClass(this.buttonClassName);
				this.addClass(this.buttonClassName + '-over');
			});
			// add event
			button.addEvent('mouseout' , function(event){
				this.removeClass(this.buttonClassName + '-over');
				this.addClass(this.buttonClassName);
			});
		}.bind(this));
	}
};

window.addEvent('domready' , function(){
	Villam.Forms.Button.stylizeAll();
});

/**
 * DropdownSelect
 */
var DropdownSelect = new Class({
	Implements: [Options, Events],

	options: {
		defaultText : 'select one...'
	},
	
	container : null,
	
	ul : null,
	
	ulInput : null,
	
	ulItems : null,
	
	selectedItem : null,
	
	display : null,
	
	fx : null,
	
	cbOnChange : [],
	
	initialize: function(container , options){
		this.container = container;
		if ($defined(options)) {
			this.setOptions(options);
		}
		this.stylize();
	},
	
	refresh: function(){
		if (!$chk(this.selectedItem)) return;
		// add checked class to selected item 
		this.selectedItem.addClass('checked');
		// refresh ulinput value
		this.ulInput.value = this.selectedItem.relatedInput.value;
		// refresh display text		
		var text = this.options.defaultText;
		if ($chk(this.selectedItem)) {
			text = this.selectedItem.get('text');
		}
		this.display.set('text', text);
		// callback
		this.cbOnChange.each(function(callback){
			callback.run([this , this.ulInput.value , text]);
		}.bind(this));
	},
	
	addOnChangeCallback: function(callback){
		this.cbOnChange.push(callback);
	},
	
	stylize: function(){
		this.ul = this.container.getElement('ul.list');
		this.ulInput =this.container.getElement('input');
		this.ulItems = this.ul.getElements('li');		
		// create display 
		this.display = new Element('div' , {
		    'class': 'display'
		});
		this.display.inject(this.ul , 'before');
		// create effect
		this.fx = new Fx.Slide(this.ul , {
			'duration' : 200
		}).hide();
		//chrome hack and absolute positioning
		this.ul.getParent().setStyles({
			'margin' : 0,
			'position' : 'absolute'
		});
		// add events to container (slide in/out) 
		this.container.addEvents({
			'mouseenter' : function(){
				this.fx.cancel();
				this.fx.slideIn();
				this.display.addClass('on');
			}.bind(this),
			'mouseleave' : function(){
				this.fx.cancel();
				this.fx.slideOut();
				this.display.removeClass('on');
			}.bind(this)
		});			
		// add events to list items
		this.ulItems.each(function(li){
			li.relatedInput = li.getElement('input');
			if (li.relatedInput.value == this.ulInput.value && !$chk(this.selectedItem)){
				this.selectedItem = li;
			} else {
				li.removeClass('checked');
			}
			this.refresh();
			li.addEvents({
				'click': function(event){
					// remove previously selected input value
					this.selectedItem.removeClass('checked');
					this.selectedItem = $(event.target);
					// refresh display
					this.refresh();
					// close select
					this.container.fireEvent('mouseleave');
				}.bind(this),
				'mouseenter' : function(event){
					$(event.target).addClass('hovered');
				},
				'mouseleave' : function(event){
					$(event.target).removeClass('hovered');
				}				
			})
		}.bind(this));
		// show villam form select
		this.container.setStyle('display', 'block'); 
	}
});

var VillamFileGroup = new Class({
	Implements : Options,
	
	options : {
		selector 				: '.villam-form-file',
		villamFilePrefix 		: 'villam-form-file-',
		duration 				: 300,
		transition 				: Fx.Transitions.Expo.easeOut,
		onNewVillamFile			: function(){},
		villamFileOptions 		: {
			
		}
	},
	
	data: {},
	
	container : null,
	
	villamFiles : [],
	
	_cloneLast : function(){
		number = this.villamFiles.length + 1;
		villamFile = this.villamFiles.getLast();
		container = villamFile.container.clone();
		container.set('id' , this.options.villamFilePrefix + number);
		container.getElement('.file-file-id').set('value' , 0);	
		container.getElement('.file-button').set('text' , VText('SELECT A DOCUMENT'));
		container.getElement('.file-number').set('text' , number + '.');
		fx = new Fx.Morph(container, {
			duration: this.options.duration, 
			transition: this.options.transition
		});
		container.inject(villamFile.container , 'after');
		containerHeight = container.getStyle('height');
		container.setStyles({
			'opacity'  : 0,
			'height' : 0
		});		
		this._addVillamFile(container);
		fx.start({
			'height' : containerHeight,
			'opacity' : 1
		}).chain(this.options.onNewVillamFile);
	},
	
	_addVillamFile : function(container){
		var options = this.options.villamFileOptions;
		options.onSubmit = function(){
			nonSelected = 0;
			this.villamFiles.each(function(vf){
				if (!vf.selected() && !vf.inprogress()){
					nonSelected++;
				}
			});
			if (nonSelected < 1){
				this._cloneLast();
			}
		}.bind(this);
		this.villamFiles.push( new VillamFile(container , options));
		this.villamFiles.getLast().ajaxUpload.setData(this.villamFiles[0].ajaxUpload._settings.data);
	},
	
	setData : function(data){
		this.villamFiles.each(function(vf){
			vf.setData(data);
		});
	},
	
	initialize : function(container , options){
		this.container = container;
		this.setOptions(options);
		this.container.getElements(this.options.selector).each(function(e){
			this._addVillamFile(e);
		}.bind(this));
	}
});

/**
 * FILE
 */
var VillamFile = new Class({
	Implements : Options,
	
	container : null,
	
	number : null,
	
	id : null,
	
	fileId : null,
	
	fileType : null,
	
	button : null,
	
	deleteButton: null,
	
	downloadButton : null,
	
	inprogressButton : null,
	
	ajaxFileInfo : null,
	
	ajaxDeleteButton : null,
	
	ajaxUpload : null,
	
	submitted : false,
	
	options: {
		action : 'index.php',
		name : 'fileforupload',
		autoSubmit: true,
		responseType: false,
		showDownloadIco : false,
		onChange : function(file, extension){},
		onSubmit : function(file, extension){},
		onComplete: function(file, response) {},
		onDeleteSubmit : function(){},
		onDeleteComplete : function(response){},
		data : {
			controller : 'file'
		}
	},
	
	selected : function(){
		return this.getFileId() > 0;
	},
	
	inprogress : function(){
		return this.submitted || this.inprogressButton.getStyle('display') != 'none'; 
	},
	
	getId : function(){
		return this.id;
	},
	
	getFileId : function(){
		return this.fileId.get('value');
	},
	
	_stylize : function(){
		// get elements
		this.id 				= this.container.get('id');
		this.number				= this.container.getElement('.file-number');		
		this.button 			= this.container.getElement('.file-button');
		this.deleteButton 		= this.container.getElement('.file-button-delete');
		this.downloadButton 	= this.container.getElement('.file-button-download-click');
		this.inprogressButton 	= this.container.getElement('.file-button-inprogress');
		this.fileId 			= this.container.getElement('.file-file-id');
		this.fileType 			= this.container.getElement('.file-file-type').get('value');
		
		// set the id of other elements based on the container id
		// add id-s
		this.fileId.set('id' , this.id + '_type');
		this.fileId.set('name' , this.id + '_type');
		// add id to button
		this.button.set('id' , this.id + '_button');
		
		this.button.removeClass('hover');	
	},
	
	_refresh : function(){
		if (this.selected()) {
			this.ajaxFileInfo.send({
				'file_id' : this.getFileId()
			})
		} else {
			this._hideIco();
		}
	},
	
	_refreshDeleteButton : function(){
		if (this.selected()){
			this.deleteButton.setStyle('display' , '');
			if (this.options.showDownloadIco){
				this.downloadButton.setStyle('display' , '');
				this.downloadButton.set('href' , this.options.action + '?' + new Hash($extend(this.options.data , {
					'task' : 'download',
					'id' : this.getFileId()
				})).toQueryString());	
			}
		} else {
			this.deleteButton.setStyle('display' , 'none');
			this.downloadButton.setStyle('display' , 'none');			
		}
	},
	
	_showIco : function(){
		this.inprogressButton.setStyle('display' , '');
		this.deleteButton.setStyle('display' , 'none');
		this.downloadButton.setStyle('display' , 'none');		
	},
	
	_hideIco : function(){
		this.inprogressButton.setStyle('display' , 'none');
		this._refreshDeleteButton();
	},	
	
	setData : function(data){
		this.ajaxUpload.setData($extend( this.ajaxUpload._settings.data , data ));
	},
	
	initialize: function(container , options){
		this.setOptions(options);
		this.container = container;
		this._stylize();
		ajaxuploaddata = $extend({} , this.options.data);
		// create ajax upload
		this.ajaxUpload = new AjaxUpload(this.button.get('id'), {
			action: this.options.action,
			name : this.options.name,
			data: $extend(ajaxuploaddata , {
				'task' : 'uploadfile',
				'file_type' : this.fileType
			}),
			autoSubmit: this.options.autoSubmit,
			responseType: this.options.responseType,
			onChange: this.options.onChange,
			onSubmit: function(file, response){
				this.submitted = true;
				if (this.options.onSubmit.run([file , response]) == false) return false;
				this.submitted = false;
				this.ajaxUpload.disable();
				this._showIco();
				return true;
			}.bind(this),
			onComplete: function(file, response){
				this.options.onComplete.run([file , response]);
				response = JSON.decode(response);
				if ($defined(response.id)) {
					this.button.innerHTML = response.filename_original;
					this.fileId.value = response.id;
				} else {
					this.ajaxUpload.enable();
					messageBox.show( $extend( {
						buttons : [
							{ title : VText('Ok') }
						]
					} , response.box ) );
				}
				this._hideIco();
			}.bind(this)
		});
		// create ajax delete button
		deletebuttondata = $extend({} , this.options.data);
		this.ajaxDeleteButton = new AJAXCall({
			url : this.options.action,
			data : $extend(deletebuttondata , {
				'task' : 'deletefile'
			})
		});
		this.ajaxDeleteButton.addEvents({
			'request' : function(){
				if (this.options.onDeleteSubmit.run() == false) return false;
				this._showIco();
			}.bind(this),
			'complete' : function(response){
				if (this.options.onDeleteComplete.run(response) == false) return false;
				if ( $defined( response.id ) ) {
					this.ajaxUpload.enable();
					this.button.set('text' , VText('SELECT A DOCUMENT'));
					this.fileId.value = 0;
				} else {
					messageBox.show( $extend( {
						buttons : [
							{ title : VText('Ok') }
						]
					} , response.box ) );
				}
				this._hideIco();				
			}.bind(this)
		});					
		// delete		
		fileinfodata = $extend({} , this.options.data);
		this.deleteButton.addEvent('click',function(){
			this.ajaxDeleteButton.send({
				'file_id' : this.getFileId()
			});
		}.bind(this));		
		// create ajax fileinfo
		this.ajaxFileInfo = new AJAXCall({
			url : this.options.action,			
			data : $extend(fileinfodata , {
				'task' : 'fileinfo'
			})
		});	
		this.ajaxFileInfo.addEvents({
			'request': function(){
				this.ajaxUpload.disable();
				this._showIco();
			}.bind(this),			
			'complete' : function(response){
				if ($defined(response.id)){
					this.button.innerHTML = response.filename_original;					
				} else {
					this.ajaxUpload.enable();
				}
				this._hideIco();
			}.bind(this)
		});
		this._refreshDeleteButton();
		this._refresh();
	}
})
