﻿/*key*/	
Event.keys.virgola = 188;
Event.keys.punto = 190;
Event.keys.pad0 = 96;
Event.keys.pad1 = 97;
Event.keys.pad2 = 98;
Event.keys.pad3 = 99;
Event.keys.pad4 = 100;
Event.keys.pad5 = 101;
Event.keys.pad6 = 102;
Event.keys.pad7 = 103;
Event.keys.pad8 = 104;
Event.keys.pad9 = 105;
Event.keys.padPunto = 110;

/*key array*/
var arrKeyNumber= ['0','1','2','3','4','5','6','7','8','9','pad0','pad1','pad2','pad3','pad4','pad5','pad6','pad7','pad8','pad9'];
var arrKeyAlphaLcase= ['a','b','c','d','e','f','g','h','i','l','m','n','o','p','q','r','s','t','u','v','z','k','j','x','y','w'];
var arrKeyAlphaUcase= ['A','B','C','D','E','F','G','H','I','L','M','N','O','P','Q','R','S','T','U','V','Z','K','J','X','Y','W'];
var arrKeyValuta= ['0','1','2','3','4','5','6','7','8','9','pad0','pad1','pad2','pad3','pad4','pad5','pad6','pad7','pad8','pad9','virgola'];
var arrKeyArrow= ['left','up','down','right'];
var arrKeySpecial= ['backspace','delete'];

//ELEMENT EXTEND
Element.extend({	
  /*rimuovi un elemento di style*/
  removeStyle: function(styleName) {
		var newStyle='';
		this.style.cssText.split(';').each(function(itemStyle){
			if(String.trim(itemStyle.split(':')[0]).toLowerCase() !='display' && String.trim(itemStyle) != ''){
				(newStyle == '') ?  newStyle+=itemStyle : newStyle+=';'+itemStyle;
			}
		})
		
		this.style.cssText =newStyle;
		
  },

  /*nascondi*/
  nascondi: function() {
    this.setStyle('display','none');		
  },
  /*mostra*/
  mostra: function() {
	this.setStyle('display','block');
  },
  
  /*toggle display*/
  toggleDisplay: function() {
	if(this.getStyle('display')=='none'){
		this.setStyle('display','block');
	}else{
		this.setStyle('display','none');		
	}
  },
 
  /* Dispone al centro della pagina un oggetto*/
	centroPagina:function(){
		var wScr = window.getWidth()/2;
		var hScr = window.getHeight()/2;
		var hLogo=Number.toInt(this.getStyle('height'))/2; 		
		var wLogo=Number.toInt(this.getStyle('width'))/2; 				
		var y=hScr-hLogo-50;			
		var x=wScr-wLogo;		
		this.setStyles({position: 'absolute',left:x,top:y});	
	},
  /*mette un imput in reader*/
	setReadOnly:function(bool){
		if(bool){
			this.setProperty('readonly','readonly')
			this.addClass('readOnly')
		}else{
			this.removeClass('readOnly')
			this.removeProperty('readonly')
		}
	},
  /*testa se un input è in readonly*/
	isReadOnly:function(){
			return this.getProperty('readonly')
	},
	computedPosition:function(element,options){
		
		this.options = $merge({
			'position': 'RC',
			'height': Number.toInt(element.getStyle('height')),
			'width': Number.toInt(element.getStyle('width')),
			'distance': 5
		}, options);
				
		this.coord =this.getCoordinates()
		var left=0;
		var top=0;

		switch(this.options.position.toUpperCase()){
			case 'RC':
				left=this.coord.left+this.coord.width+this.options.distance;
				top=(this.coord.top+(this.coord.height/2))-(this.options.height/2);
				break;
			case 'RT':
				left=this.coord.left+this.coord.width+this.options.distance;
				top=this.coord.top;
				break;
			case 'D2':
				left=this.coord.left+this.coord.width+this.options.distance;
				top=this.coord.top-this.options.height-this.options.distance;
				break;
			case 'TR':
				left=this.coord.left+this.coord.width-this.options.width;
				top=this.coord.top-this.options.height-this.options.distance;
				break;
			case 'CT':
				left=(this.coord.left+(this.coord.width/2))-(this.options.width/2);
				top=this.coord.top-this.options.height-this.options.distance;
				break;
			case 'TL':
				left=this.coord.left;
				top=this.coord.top-this.options.height-this.options.distance;
				break;
			case 'D1':
				left=this.coord.left-this.options.width-this.options.distance;
				top=this.coord.top-this.options.height-this.options.distance;
				break;
			case 'LT':
				left=this.coord.left-this.options.width -this.options.distance;
				top=this.coord.top;
				break;
			case 'LC':
				left=this.coord.left-this.options.width -this.options.distance;
				top=(this.coord.top+(this.coord.height/2))-(this.options.height/2);
				break;
			case 'LB':
				left=this.coord.left-this.options.width -this.options.distance;
				top=this.coord.top+this.coord.height-this.options.height;
				break;
			case 'D3':
				left=this.coord.left-this.options.width -this.options.distance;
				top=this.coord.top+this.coord.height+this.options.distance;
				break;
			case 'BL':
				left=this.coord.left;
				top=this.coord.top+this.coord.height+this.options.distance;
				break;
			case 'CB':
				left=(this.coord.left+(this.coord.width/2))-(this.options.width/2);
				top=this.coord.top+this.coord.height+this.options.distance;
				break;
			case 'BR':
				left=this.coord.left+this.coord.width-this.options.width;
				top=this.coord.top+this.coord.height+this.options.distance;
				break;
			case 'D4':
				left=this.coord.left+this.coord.width+this.options.distance;
				top=this.coord.top+this.coord.height+this.options.distance;
				break;
			case 'RB':
				left=this.coord.left+this.coord.width+this.options.distance;
				top=this.coord.top+this.coord.height-this.options.height;
				break;
		}
		
		element.setStyles({		   
			'top': top,
			'left': left,
			'position': 'absolute'
		});
	}
});

Utility = new Abstract({
	chkMail:function (EmailAddr){
		var Filtro = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-]{2,})+\.)+([a-zA-Z0-9]{2,})+$/;
		if (Filtro.test(EmailAddr))
		return true;
		else
		{
			return false;
		}
	}
})


//STRING EXTEND
String.extend({
	replaceAllSub:function(rplString,search){//sostituisce tutte le occorrrenze trovate
		result= this;
		while(result.contains(rplString)){
			result = result.replace(rplString,search);
		}
		return result
	},
	toProperCase:function(){
	  return this.toLowerCase().replace(/^(.)|\s(.)/g, function($1) { return $1.toUpperCase(); });
	}
});	
String.extend({
		formatValutaEuro:function(){//formatta una stringa  in euro
				if(String.trim(this)==''){						
					return this;
				}
				//decimali
				var decimali= (this.split(',')[1]==null) ? '' :this.split(',')[1]
				switch(decimali.length)
				{				
				case 0:
				  decimali=decimali+"00"
				  break;
				case 1:
				  decimali=decimali+"0"
				  break;
				}	
				//intero
				var intero=this.split(',')[0]
				var k=0
				var newIntero='';
				for(i=intero.length-1;i>=0;i--){
					ch= intero.charAt(i)
					if(k==3){
						newIntero = ch+'.'+newIntero;
						k=0
					}else{
						newIntero = ch+newIntero;
					
					}
					k++;
				}
				return newIntero+','+decimali
				 
		}
});	
//COMMON FIELDS
Element.extend({
	fieldCurrency: function() { //trasforma un input in un currency
		var regexp =/^\d+[\,]{0,1}\d{0,2}$/;
		this.addEvent('keydown', function(event){			
			event = new Event(event);				
			
			if(!(arrKeyValuta.contains(event.key) || arrKeyArrow.contains(event.key) || arrKeySpecial.contains(event.key))){
				event.stop()
			}		
		})
		this.addEvent('keyup', function(event){				
			if(this.value.test(regexp)){
				this.setStyle('color','black')
			}else{
				this.setStyle('color','red')
			}
		})
		this.addEvent('blur', function(event){	
				var val = this.getProperty('value');
				if(val.test(regexp) && val!=""){	 				
				 this.setProperty('value',String.formatValutaEuro(val));
				} 
				
		})
    },	
	fieldNumber: function() { //trasforma un input in un currency		
		this.addEvent('keydown', function(event){			
			event = new Event(event);				
			if(!(arrKeyNumber.contains(event.key) || arrKeyArrow.contains(event.key) || arrKeySpecial.contains(event.key))){
				event.stop()
			}		
	})
  }
})  
//TIPS UI IMAGE 
TipsUI = new Class({
	initialize: function(options){
		this.id='tips'+$random(1,1000);
		this.options = $merge({
			'classe': 'tips',
			'level': 1,
			'duration': 300
		}, options);
		
		this.divTips=new Element('div', {
			'styles': {
			'opacity': 0,
			'z-index': this.options.level
			},
			'id':this.id
		});		
		this.fxTips = new Fx.Style(this.divTips, 'opacity',{
				duration:this.options.duration
			});
	},
	prompt:function(element,variables){
		this.variables = $merge({			
			'testo': '[[Testo da inserire nel mesaggio!!]]',
			'type':'text',
			'height':13,
			'width':160,
			'opacityEnd':1,
			'srcImage':'',
			'position':'rc',
			'duration':'',
			'distance':5
		}, variables);
		switch(this.variables.type){
			case 'image':
				this.image();
				break
			case 'text':
				this.text();
				break
		}
		
		if(this.variables.duration !='') this.fxTips.options.duration=this.variables.duration
		this.fxTips.set(0)
		this.element = $(element);
		this.element.computedPosition(this.divTips,{
			'position':this.variables.position,
			'height':this.variables.height,
			'width':this.variables.width,
			'distance':this.variables.distance
			});


		if(!$chk(($(this.id)))) window.addInWindow(this.divTips)
		this.fxTips.stop();
		this.fxTips.start(0,this.variables.opacityEnd)
	},
	image:function(){
		this.divTips.setStyles({
			'height':this.variables.height,
			'width':this.variables.width,
			'background':'transparent url('+this.variables.srcImage+') no-repeat center center'
		})		
	},
	text:function(){
		this.divTips.setStyles({
			'height':this.variables.height,
			'width':this.variables.width
		})		
		this.divTips.addClass(this.options.classe)		
		this.divTips.setHTML(this.variables.testo)
	},
	hide:function(){
		this.fxTips.set(0)
	}
}); 

//WINDOW EXTEND
window.extend({
	lockWindow: function(options) { //mette l'oggetto in primo piano e blocca la finestra		
		if(this.isLockWindow()) return
		//options		
		this.options = $merge({			
			'duration':(!$defined(this.variable)) ? 100 : this.variable.durationLockWindow,
			'opacityEnd':(!$defined(this.variable)) ? 0.5 :this.variable.opacityEndLockWindow,
			'color': (!$defined(this.variable)) ? 'black' : this.variable.colorLockWindow,
			'level': 1,
			'load':false			
		}, options);
		
		
		
		
		this.w=this.getScrollWidth()
		this.h=this.getScrollHeight()	
		this.divOverScreen=new Element('div', {
			    'styles': {
				'display': 'block',
				'width': this.w,
				'height': this.h,
				'background-color': this.options.color,
				'position': 'absolute',
				'left': 0,
				'top': 0,
				'opacity': 0,
				'z-index': this.options.level
			    }	
			}
		);
		this.divOverScreen.setProperty('id','lockWindow')
		$E('body').appendChild(this.divOverScreen);	
		this.fx = new Fx.Styles(this.divOverScreen, {
					duration:this.options.duration, 
					wait:false
				})		
					
		this.fx.start({
			'opacity':this.options.opacityEnd
		});
		
		if(this.options.load) this.setWindowLoad();
		this.addEvent('resize',this.resizer)
	},
	resizer:function(){
		this.divOverScreen.setStyles({
			width: this.getScrollWidth(),
			height: this.getScrollHeight()
		});
	},
	setWindowLoad:function(options){
		this.options = $merge({
			'level': 1
		}, options);
		this.divLoad=new Element('div', {
				'styles': {
				'display': 'block',
				'background-image': 'url(image/ajaxloader3.gif)',
				'background-position': 'center center',
				'background-repeat': 'no-repeat',
				'width': 100,
				'height': 100,
				'position': 'absolute',
				'z-index': this.options.level+1
				}	
			}
		);
		this.divLoad.setProperty('id','lockWindowLoad')			
		$E('body').appendChild(this.divLoad);
		this.divLoad.centroPagina()
		this.fxLoad = new Fx.Style('lockWindowLoad', 'opacity',{duration:100}).set(0);
		this.fxLoad.start(1);
	},
	unlockWindow: function() { //sblocca la finestra eliminando l'oggetto in primo piano e anche l'oggetto di loading
		window.removeEvent('resize',this.resizer)
		if($chk($('lockWindow'))) $('lockWindow').remove()		
		if($chk($('lockWindowLoad'))) $('lockWindowLoad').remove()		
	},
	unlockWindowLoad: function() { //rimuovel 'oggetto di loading	
		if($chk($('lockWindowLoad'))) $('lockWindowLoad').remove()		
	},
	insertElmentInDocument:function(element){
		element.appendChild(this.divLoad);
	},
	isLockWindow:function(){
		return $chk($('lockWindow'));
	},
	addInWindow:function(obj){		
		$E('body').appendChild(obj);
	},
	getQueryString:function(){
		var arr= new Hash();
		if(window.location.search.contains('?')){
			var qry=window.location.search.split('?')[1]
		}	
		(qry.split('&')).each(function(v){
			arr.set(v.split('=')[0],v.split('=')[1])			
		})		
		return arr;		
	},
	setApplicationVariable:function(variable){
		this.variable = $merge({
			'colorLockWindow':'black',
			'durationLockWindow':70,
			'opacityEndLockWindow':0.5
		}, variable);
	}
}); 


//FX LAYER.OVER
Fx.LayerOver = new Class({
	initialize: function(element,content,options){
		this.options = $merge({
			'x': 0,
			'y': 0,
			'opacityStart': 0.001,
			'opacityEnd': 1,
			'duration': 300,
			'durationShowContent': 100,
			'heightEnd': 500,
			'widthEnd': 500,
			'heightStart': 20,
			'widthSart': 20,
			'closeDelay': 1000,		
			'level': 1,		
			'transition': Fx.Transitions.Quart.easeOut
		}, options);
		this.element=$(element)		
		this.content=$(content);
		this.canClose = true;		
		this.myTimer=0;
		this.state='close';		
		this.content.setOpacity(0);
		this.element.setOpacity(this.options.opacityStart);
		this.element.setStyles({position: 'absolute',
								left: this.options.x,
								top: this.options.y,
								width:this.options.widthSart,
								height:this.options.heightStart,
								'z-index':this.options.level,
								overflow:'hidden'
								});	
		this.fx= new Fx.Styles(this.element, {transition :this.options.transition,
									  duration:this.options.duration, 
									  wait:false										
									   }).addEvent('endThisEvent',this.setState.bind(this)).addEvent('onComplete',this.menageContent.bind(this));	
		this.fxContent = new Fx.Styles(this.content,{duration:this.options.durationShowContent,wait:false})		
		this.element.addEvent('mouseenter', this.open.bind(this))
		this.element.addEvent('mouseleave', this.close.bind(this));
		
	},
	open: function(){		
		$clear(this.myTimer)
		if(this.state=='close'){
			window.lockWindow()
		}
		this.fx.start({					
			'height':this.options.heightEnd,									
			'width':this.options.widthEnd,	
			'opacity':this.options.opacityEnd		
		}).fireEvent('endThisEvent','open');
			
	},
	close: function(){
		if(this.canClose){
			myf= this.closeDelay.create({delay:this.options.closeDelay});
			this.myTimer= myf(this);
		}
	},
	closeDelay:function(parent){
		window.unlockWindow()
		parent.content.setOpacity(0);
		parent.fx.start({
			'height':parent.options.heightStart,
			'width':parent.options.widthSart,
			'opacity':parent.options.opacityStart
		}).fireEvent('endThisEvent','close');
	},
	setCanClose:function(val){
		this.canClose=val
	},
	setState:function(newState){
		this.state = newState		
	},
	menageContent:function(){
		if(this.state=='open'){			
			this.fxContent.start({					
				'opacity':1	
			})
		}		
	}
});

//FX.MGSBOX
TypeMsgBox = new Abstract({
	'Ok': {key:1,image:'image/msgbox/ok.gif'},
	'Error': {key:2,image:'image/msgbox/error.gif'},
	'Warning': {key:3,image:'image/msgbox/warning.gif'},
	'Question': {key:3,image:'image/msgbox/question.gif'}
});

MsgBox = new Class({
	initialize: function(options){
		this.options = $merge({
			'classe': 'msgbox'
		}, options);
		
		this.id = $random(1,1000)+'_msgbox'		
		this.buttonList=[['Ok','close']]			
		this.divMsgBoxContent=new Element('div', {'id':this.id,
				'styles': {													
				'position': 'absolute'
				}	
		});
		//setto il tasto esc per chiudere il msgbox
		/*
		this.divMsgBoxContent.addEvent('keypress',function(event){
			var event = new Event(event)
			if(event.key=='esc') this.close();
		}.bind(this))*/
		//contenitore		
		this.divMsgBoxContent.addClass(this.options.classe);

		//DIV text
		this.divMsgBoxText =new Element('div',{'class':'text'});												
		this.divMsgBoxText.injectInside (this.divMsgBoxContent);

		//DIV bottoni
		this.divMsgBoxButton =new Element('div',{'class':'buttons'});				
		this.divMsgBoxButton.injectInside (this.divMsgBoxContent);	
		//table bottoni
		this.tableMsgBoxButton =new Element('table',{'align':'center'});
		this.tableMsgBoxButton.injectInside (this.divMsgBoxButton);
		//tbody	bottoni
		this.tBodyMsgBoxButton =new Element('tbody');
		this.tBodyMsgBoxButton.injectInside (this.tableMsgBoxButton);	
		//tr	bottoni
		this.trMsgBoxButton =new Element('tr');
		this.trMsgBoxButton.injectInside (this.tBodyMsgBoxButton);		
		
	},
	prompt:function(options){			
		promptOptions = $merge({
			'testo': '[[Testo da inserire nel mesaggio!!]]',
			'buttonList': [['Chiudi','close']],
			'type': TypeMsgBox.Ok,
			'width': 450,
			'delay': 100,
			'level': 5
		}, options);		
		this.divMsgBoxText.setStyles({
			'background-image':'url('+promptOptions.type['image']+')',
			'background-repeat':'no-repeat',
			'background-position':'right center'
		})			
		this.divMsgBoxContent.setStyle('width',promptOptions.width) 		
		this.divMsgBoxContent.setStyle('z-index',promptOptions.level) 	
		
		//pulisco i bottoni precedenti
		this.trMsgBoxButton.getChildren().each(function(item){item.remove()})
		//inserisco i bottoni
		
		
		promptOptions.buttonList.each(function(item,index){		
			var td = new Element('td');
			var bt= new Element('a',{'class':'button','href':'javascript:void(0)'})
			
			bt.appendText(item[0])
			
			switch(item[1]){
			 case 'close':
				bt.addEvent('click',this.close.bind(this));
				break;	
			 default:
				bt.addEvent('click',item[1])
				//bt.addEvent('click',this.close.bind(this));
			}

			bt.injectInside(td)			
			td.injectInside(this.trMsgBoxButton);					
		}.bind(this));	
		window.lockWindow();
		//pulisco il testo precedente
		this.divMsgBoxText.getChildren().each(function(item){item.remove()})
		//aggiungo il testo
		var texts= promptOptions.testo.split('/wrap/')
		for(i=0;i<texts.length;i++){
			new Element('div').appendText(texts[i]).injectInside(this.divMsgBoxText)
		}	
		var sh=this.show.create({'delay':promptOptions.delay,'bind':this});
		sh();
		
	},
	close:function(){
		this.divMsgBoxContent.remove();
		window.unlockWindow();
		window.removeEvent('resize',this.monitorPosition.bind(this))
	},
	closeMsgBox:function(){
		this.divMsgBoxContent.remove();		
		window.removeEvent('resize',this.monitorPosition.bind(this))
	},
	
	show:function(){
		//inserisco il DIV nel documento
		$E('body').appendChild(this.divMsgBoxContent);				
		this.divMsgBoxContent.centroPagina();
		//focus sul primo bottone
		this.trMsgBoxButton.getElements('a')[0].focus()	
		this.fxMove = new Fx.Styles(this.id , {duration: 300,transition: Fx.Transitions.Cubic.easeInOut});		
		window.addEvent('resize',this.monitorPosition.bind(this))
	},
	monitorPosition:function(){
		var wScr = window.getWidth()/2;
		var hScr = window.getHeight()/2;
		var hMsgBox=Number.toInt(this.divMsgBoxContent.getStyle('height'))/2; 		
		var wMsgBox=Number.toInt(this.divMsgBoxContent.getStyle('width'))/2; 				
		var y=hScr-hMsgBox-50;			
		if(y<0) y=0;
		if(x<0) x=0;
		var x=wScr-wMsgBox;					
		this.fxMove.start({
			'top': y,
			'left':x
			});
	}
	
})


//XML CLASS
XmlRead  = new Abstract({
	getXmlTag: function(elStart,idElement){
					return elStart.getElementsByTagName(idElement).item(0);
				},
	getXmlTagValue: function(elStart){						
						return elStart.firstChild.nodeValue
					},
	chkXmlTag:function(elStart,idElement){
			return (elStart.getElementsByTagName(idElement).item(0)) ? true : false;
		},
	count:function(element){
		return element.childNodes.length
	}	
});

//CLASS MENU

MenuUI = new Class({
	
	initialize: function(element,className,options){
		this.options = $merge({			
			'eventShow': 'mouseenter',
			'level': 1
		}, options);
		
		this.closeDelay=0;
		this.hashItem = new Hash();
		this.idElement=element+'_list';		
		($(element)) ? this.element = $(element) : alert('Nessun aggancio su ['+element+']');
		
		this.coord= this.element.getCoordinates();
		(window.ie) ? this.offset= 1 : this.offset= 0;
		this.canClose = true;
		this.menu=new Element('div', {
			'styles': {							
			'border-collapse': 'collapse',								
			'position': 'absolute',
			'z-index': this.options.level,
			'display':'none',
			'top': this.coord.top+this.coord.height+this.offset,
			'left': this.coord.left		
			},			
			'class':className,
			'id':this.idElement
		});		
		this.menu.addEvent('mouseenter',function(){			
			$clear(this.closeDelay)
		
		}.bind(this))	
		this.menu.addEvent('mouseleave',function(){
			this.hide();
		
		}.bind(this))		
		this.element.addEvent(this.options.eventShow, function(event){	
			$E('body').getElements('div[id$=_list]').each(function(item){				
				item.nascondi();
			}.bind(this))
			this.show();
		}.bind(this));
		this.element.addEvent('mouseleave', function(event){	
			var fh = this.hide.create({delay:500,bind:this});
			this.closeDelay = fh();	
					
		}.bind(this));
		//this.menu.injectInside(this.element.parentNode);				
		window.addInWindow(this.menu)
	},	
	addItem:function (options){
		var itemOptions = $merge({
			'testo': 'voce menu',			
			'onclick': Class.empty,
			'image': '',
			'href': 'javascript:void(0)'
		}, options);
		
		
		var item= new Element('a',{'href':itemOptions.href,'styles':{'display':'block'}});
		
		item.appendText(itemOptions.testo)
		item.addEvent('click',itemOptions.onclick);
		item.addEvent('click',function(){
			this.hide()
			this.hashItem.get(itemOptions.testo).blur()
		}.bind(this))
		
		var itemDiv = new Element('div');
		
		if(itemOptions.image!=''){
			var itemIcon = new Element('img',{'src':itemOptions.image,'styles':{
				'margin-left':3,
				'margin-top':5,				
				'float':'left'
				}});
			itemIcon.injectInside(itemDiv)
		}

		item.injectInside(itemDiv)
		itemDiv.injectInside(this.menu)
		this.hashItem.set(itemOptions.testo,item)				
	},
	show:function(){			
		this.menu.mostra()
	},
	hide:function(){					
		this.menu.nascondi();
	},
	focus:function(key){
		this.hashItem.get(key).addClass('select')
	}
	
});

//TABLE LIST CLASS
var TableList =  new Class({
	initialize: function(element,options){
		this.options = $merge({
			'altTr': 'alt',
			'idBtFilterDelete': 'filterDelete',
			'inputIdSearch': 'searchElement',
			'altOver': 'over',
			'altSel': 'selected',
			'durationCookie': 360000,
			'url': 'mod.php?v=macro'
		}, options);
		if($chk($(element))) this.element =$(element);
		this.tfoot=this.element.getElement('tfoot');
		this.tbody=this.element.getElement('tbody');
		this.thead=this.element.getElement('thead');
		
		this.ordinamento='';
		this.colonna='';
		this.page='';
		this.deleteFilter='';
		this.searchFilter='';
		this.colonneHash = new Hash();
		this.filterHashKey = new Hash();
		
		i=0;
		
		
		//aggancio la funzione per il filtro sulle elimniate
		if($chk($(this.options.idBtFilterDelete))){
			$(this.options.idBtFilterDelete).setStyle('width',100)
			this.btFilterDelete = new SelectCustom(this.options.idBtFilterDelete,{'onChange':function(){
				this.setFilterDelete()
			}.bind(this)})			
			this.btFilterDelete.addItem('No','0')
			this.btFilterDelete.addItem('Si','1')
			this.btFilterDelete.addItem('Solo Eliminate','2')
			this.btFilterDelete.setKeyDefault('0')
		}
		
		//ricerca		
		var textDefaultSearch = 'Cerca...'
		this.searchInput = $(this.options.inputIdSearch)
		if($chk(this.searchInput)){
			this.searchInput.value=textDefaultSearch;
			this.searchInput.addEvent('focus',function(){			
					if(this.searchInput.value==textDefaultSearch)this.searchInput.value=''
					this.searchInput.addClass('focus')
			}.bind(this))
			this.searchInput.addEvent('blur',function(){
				if(this.searchInput.value=='')this.searchInput.value=textDefaultSearch
				this.searchInput.removeClass('focus');
			}.bind(this))
			this.searchInput.addEvent('keydown',function(event){
				event = new Event(event);
				if(event.key == 'enter') this.setFilterSearch(this.searchInput.getProperty('value'));
			}.bind(this))
			
		}
		
		//query string
		this.queryString = window.getQueryString();
	
		//setto il width in base al monitor
		this.element.setStyle('width',window.getWidth()-2)
		
		//norecord
		var noRecord = this.element.getElements('div[class=noRecord]');		
		if(noRecord) noRecord.centroPagina();		
		window.addEvent('resize',function(){
			if(noRecord) noRecord.centroPagina();
		}.bind(this))
		
		//cusatom check box
		this.element.getElements('input[type=checkbox]').each(function(item,index){
			item.checked =false
			item.setCustomCheckBox()
		})
	

		


		
		//elemento di select ALL
		this.selectAll = this.element.getElements('input[id=selectAll]')
			if($chk(this.selectAll)){
			this.selectAll.addEvent('click',function(){			
				if(this.selectAll.getProperty('checked').toString()=='true'){
					this.selectAllFn();
				}else{
					this.deSelectAllFn();
				}
			}.bind(this))
		}
		
		//collegamenti al form
		if(this.tbody){
			this.tbody.getElements('tr').each(function(itemTr){		
				if(itemTr.getElements('th')==''){
					var cBok = itemTr.getFirst().getFirst();
					if(i==0){	
						itemTr.addClass(this.options.altTr);
						i++
					}else{
						i--;
					}						
					itemTr.getElements('.link').each(function(itemTd){
						itemTd.setStyle('cursor','pointer')
						itemTd.addEvent('click',function(){
							redirectInterface.setUrl(this.options.url+'&op=form&id='+itemTr.getProperty('id').split('_')[1])
							redirectInterface.go()	
						}.bind(this))
					}.bind(this))
					
					itemTr.addEvent('mouseenter',function(){
						itemTr.addClass(this.options.altOver)
					}.bind(this))	
					itemTr.addEvent('mouseleave',function(){				
						if(!cBok.checked) itemTr.removeClass(this.options.altOver)					
					}.bind(this))
					cBok.addEvent('click',function(){	
						(cBok.checked) ? itemTr.addClass(this.options.altSel) : itemTr.removeClass(this.options.altSel);itemTr.removeClass(this.options.altOver)
					}.bind(this))
				}
			}.bind(this))
		}
		
		

		
		//setto la colonna attualmente ordinata e le variabili della classe per l'odinamento attualemte in query string
		if(this.queryString.get('col')){	
			this.colonna = this.queryString.get('col');
			this.ordinamento = this.queryString.get('ord');
			var thSort = this.element.getElement('th[id='+this.queryString.get('col')+']');
			thSort.addClass(this.ordinamento);
		}		

		//setto il filtro delete filter in query string
		if(this.queryString.get('delflt')){
			this.deleteFilter = this.queryString.get('delflt');			
			this.btFilterDelete.setKey(this.deleteFilter)
		}
		//setto il filtro search  filter in query string
		if(this.queryString.get('search')){
			this.searchFilter = this.queryString.get('search');
			this.searchInput.setProperty('value',this.searchFilter)
			//aggiungo il remove del filtro
			this.removeSearchFilter = new Element('div',{'id':'ciao','styles':{
				'height':19,
				'width':19,
				'background-image':'url(image/list/removeFilter.gif)',
				'background-repeat':'no-repeat',
				'background-position':'center',
				'position':'absolute',
				'cursor':'pointer'
				}				
			})
			this.removeSearchFilter.addEvent('click',function(){
				this.searchInput.setProperty('value','');
				this.setFilterSearch();
			}.bind(this))
			this.searchInput.computedPosition(this.removeSearchFilter,{'position':'d2','distance':-8})
			window.addEvent('resize',function(){
				this.searchInput.computedPosition(this.removeSearchFilter,{'position':'d2','distance':-8})
			}.bind(this))
			window.addInWindow(this.removeSearchFilter);
		}
		
		//setto la pagina  attualmente in query string  nella classe
		(this.queryString.get('pag')) ? this.page = Number.toInt(this.queryString.get('pag')) :	this.page=1
		
		
		
		if($chk(this.thead)){
			//incapsulazione nei DIV delle colonne e delel celle non FIXED
			this.thead.getElements('th').each(function(itemTh,index){				
				if(!itemTh.hasClass('fixed')) {
					var divOverflowTh = new Element('div',{'styles':{'overflow':'hidden'}});
					if($type(itemTh.firstChild)=='textnode'){
						var value = itemTh.firstChild.nodeValue;
						itemTh.innerHTML='';
						divOverflowTh.appendText(value)
						divOverflowTh.injectInside(itemTh)
					}
					
					this.tbody.getElements('tr').each(function(itemTr){
						var divOverflowTd = new Element('div',{'styles':{'overflow':'hidden'}});
						itemTd=itemTr.getElements('td')[index]
						
						if($type(itemTd.firstChild)=='textnode'){
							value = itemTd.firstChild.nodeValue;							
							itemTd.innerHTML='';
							divOverflowTd.appendText(value)
							divOverflowTd.injectInside(itemTd)
						}
					})
					
				}
			}.bind(this))
		
			//applico i dimensionamenti alle colone							
			i=0
			this.thead.getElements('th').each(function(itemTh){
				if($chk(itemTh.getAttribute('width'))){
					var w=itemTh.getAttribute('width');
					itemTh.removeAttribute('width');
					itemTh.setStyle('width',Number.toInt(w));					
				}else{
					itemTh.setStyle('width',itemTh.getStyle('width'));
				}
				//applico le classi numerate ai th
				//alimento l'hash delle colonne
				this.colonneHash.set(i+1,itemTh)

				i++;
			}.bind(this))
			
			//faccio  l'overrride delle dimensioni che trovo nei cookie
			i=1
			this.colonneHash.each(function(){				
				var ck= new Hash.Cookie(this.element.getProperty('id')+'col_'+i, {duration: this.options.durationCookie});
				if(!this.colonneHash.get(i).hasClass('fixed')){
					if(ck.get('width') != null){
					
						this.colonneHash.get(i).setStyle('width',ck.get('width'))
						
					}	
				}
				i++;
			}.bind(this))
			
			//colonne ridimensionabili
			this.colonneHash.each(function(itemTh,index){
				if(itemTh.hasClass('resizable')){
					var grip = new Element('div',
						{
						'styles':{
							
							'height':itemTh.getCoordinates().height,
							'width':5,
							'position':'absolute',
							'cursor':'e-resize'
						}
					});
					grip.setAttribute('id','gripTable_'+index)					
					grip.setStyles({
						'top':Number.toInt(itemTh.getCoordinates().top),
						'left':Number.toInt(itemTh.getCoordinates().left+itemTh.getCoordinates().width-Number.toInt(grip.getStyle('width')))+1
					})
					window.addInWindow(grip)
					
					new Drag.Base(grip,{
						limit: {x: [0, window.getWidth()],y: [itemTh.getCoordinates().top, itemTh.getCoordinates().top]},
						onSnap:function(){
						var itemNext=itemTh;
							do{
								itemNext = itemNext.getNext()
								if(!$chk(itemNext)) break;
							}while(itemNext.getStyle('display')=='none'|| !itemNext.hasClass('resizable')  || itemNext == null )
							
							if($chk(itemNext)){
								itemNext.setStyle('width','auto')
							}else{
								var itemNext=itemTh;
								do{
									itemNext = itemNext.getNext()
									if(!$chk(itemNext)) break;
								}while(itemNext.getStyle('display')=='none' || itemNext == null )
								itemNext.setStyle('width','auto')
							}
						},
						onDrag:function(){
							itemTh.setStyle('width',Number.toInt(this.element.getStyle('left'))-itemTh.getCoordinates().left-25)
							
						},
						onComplete:function(){
							var itemNext=itemTh;
							do{
								itemNext = itemNext.getNext()
								if(!$chk(itemNext)) break;
							}while(itemNext.getStyle('display')=='none'|| !itemNext.hasClass('resizable')  || itemNext == null )
							if($chk(itemNext)){
								itemNext.setStyle('width',Number.toInt(itemNext.getCoordinates().width)-30)
							}else{
								var itemNext=itemTh;
								do{
									itemNext = itemNext.getNext()
									if(!$chk(itemNext)) break;
								}while(itemNext.getStyle('display')=='none' || itemNext == null )
								itemNext.setStyle('width',Number.toInt(itemNext.getCoordinates().width)-30)
							}
							this.setGripPosistion();
						}.bind(this)
					})
					
					
				}	
			}.bind(this))
		
		}
		
		//colonne ordinabili
		this.element.getElements('th[class^=sortable]').each(function(thSort){
			thSort.setStyle('cursor','pointer')
			thSort.setProperty('title','Clicca per ordinare la colonna')
			thSort.addEvent('click',function(){
				(thSort.hasClass('asc')) ?this.ordinamento ='desc':	this.ordinamento ='asc';				
				this.colonna = thSort.getProperty('id');
				this.filterToQueryString();
			}.bind(this))
			thSort.addEvent('mouseenter',function(){thSort.addClass('over')
			})
			thSort.addEvent('mouseleave',function(){thSort.removeClass('over')})
		}.bind(this))
		
		if($chk(this.tfoot)){
			//formatta paginazione
			this.element.getElement('tfoot').getElements('li a').each(function(item,index){							
				var to= item.getProperty('href');
				if(to=='first') to=1
				if(to=='last') to=index-1								
				item.addEvent('click',function(event){
					event = new Event(event)
					event.stop();								
					if(this.page==to) return;
					this.setPage(to)
				}.bind(this))
				if(this.page!=to){
					item.addEvent('mouseenter',function(){
						item.addClass('red');
					})
					item.addEvent('mouseleave',function(){
						item.removeClass('red');
					})
				}else{
					item.setStyle('cursor','default')
				}
			}.bind(this))
			
			this.tfoot.getElements('li a[href='+this.page+']').addClass('select')
		}
		
		if($chk(this.tbody)){
		
			//creo il menu per la gestione delle colonne colonne
			this.linkMenuColonne = new Element('div',{'styles':{
					'width':16,
					'height':14,
					'position':'absolute',
					'cursor':'pointer',
					'left':this.colonneHash.get(1).getCoordinates().left+this.colonneHash.get(1).getCoordinates().width-16,
					'top':this.colonneHash.get(1).getCoordinates().top+this.colonneHash.get(1).getCoordinates().height-14,
					'background-image':'url(image/list/tableIcon.gif)',
					'background-position':'center center',
					'background-repeat':'no-repeat'
				}
			})
			
			this.linkMenuColonne.addEvent('click',function(){
				this.showMenuColonne();
			}.bind(this))
			window.addInWindow(this.linkMenuColonne)
			//creo il menu da visualizzare per la gestion delle colonne
			this.menuColonne = new Element('div',{'styles':{
					'position':'absolute',
					'left':this.linkMenuColonne.getCoordinates().left,
					'top':this.linkMenuColonne.getCoordinates().top+this.linkMenuColonne.getCoordinates().height+1,
					'background-color':'#EFE8C3',
					'border':'1px solid #BBBBBB'
					
				}
			})
			window.addInWindow(this.menuColonne)
			this.menuColonne.addEvent('mouseleave',function(){
				this.delayCloseMenuColonne =this.hideMenuColonne.create({'bind':this,'delay':200}).call()
			}.bind(this))
			this.menuColonne.addEvent('mouseenter',function(){
				$clear(this.delayCloseMenuColonne)
			}.bind(this))
			
			//fx di visibilità del menu colonne
			this.fxMenuColonne= new Fx.Style(this.menuColonne, 'left',{
				duration:500
			}).set(-300);

			this.tableMenuColonne = new Element('table',{'styles':{'border-collapse':'collapse'}});
			this.tableMenuColonne.injectInside(this.menuColonne)
			this.tHeadMenuColonne = new Element('thead');
			var trTitle = new Element('tr')
					
			new Element('th',{'styles':{
				'border-right':'1px solid #bbb',
				'padding':4,
				'border-bottom':'1px solid #bbb'
			}}).appendText('Colonna').injectInside(trTitle)
			
			new Element('th',{'styles':{
				'border-bottom':'1px solid #bbb',
				'padding':4
			}}).appendText('').injectInside(trTitle)
			
			trTitle.injectInside(this.tHeadMenuColonne)
			this.tHeadMenuColonne.injectInside(this.tableMenuColonne)		
			this.tBodyMenuColonne= new Element('tbody')
			this.tBodyMenuColonne.injectInside(this.tableMenuColonne)


			//colonne
			i=1
			this.colonneHash.each(function(itemColonna){
				
				var nomeColonna;			
				if($type(itemColonna.firstChild) == 'textnode') nomeColonna=itemColonna.firstChild.nodeValue;
				if($type(itemColonna.firstChild) == 'element') {
					//colonna con gli input
					if($(itemColonna.firstChild).getTag() =='input')  nomeColonna ='no';
					
					if($(itemColonna.firstChild).getTag()=='div') {
						if($type(itemColonna.firstChild.firstChild)) nomeColonna=itemColonna.firstChild.firstChild.nodeValue;
					}	
				}
				
				//colonna senza titolo
				if(!$type(itemColonna.firstChild)) nomeColonna ='no';
				
				if(nomeColonna != 'no' && $chk(nomeColonna)){
					var trColonna = new Element('tr');
					trColonna.injectInside(this.tBodyMenuColonne)
					
					new Element('td',{'styles':{
						'border-bottom':'1px solid #bbb',
						'background-color':'#E1EBED',
						'padding':4
					}}).appendText(nomeColonna).injectInside(trColonna)
					
					var c1 = new Element('td',{'styles':{
						'border-bottom':'1px solid #bbb',
						'border-left':'1px solid #bbb',
						'background-color':'#F5FAFA',
						'text-align':'center',
						'padding':4
						}
					})
									
					
					
					var chkBoxHideShowCol= new Element('input',{
						'type':'checkbox',
						'id':i
					})
					c1.injectInside(trColonna)
					chkBoxHideShowCol.injectInside(c1)
					
					
					chkBoxHideShowCol.setProperty('checked',true)
					
					var col = new Hash.Cookie(this.element.getProperty('id')+'col_'+i, {duration: this.options.durationCookie});
					
					if(col.get('hide') =='1'){ 
						chkBoxHideShowCol.setProperty('checked',false)
						this.hideColumn(i)
					}else{					
						if(itemColonna.hasClass('hidden') && col.get('hide') != 0) {
							chkBoxHideShowCol.setProperty('checked',false)
							this.hideColumn(i)
						}
					}				
					chkBoxHideShowCol.addEvent('click',function(){
						if(chkBoxHideShowCol.checked) {					
							this.showColumn(chkBoxHideShowCol.getProperty('id'))
							col.set('hide', '0');
							
						}else{
							col.set('hide', '1');
							this.hideColumn(chkBoxHideShowCol.getProperty('id'),true)
							
						}
					}.bind(this))
					chkBoxHideShowCol.setCustomCheckBox()
					
				}
				i++;
			}.bind(this))
			

			
			
			var chiudiTableMenuColonne = new Element('div',{
				'styles':{
					'padding':3,
					'text-align':'right',
					'cursor':'pointer',
					'text-decoration':'underline'
				}
			}).appendText('Chiudi').addEvent('click',function(){
				this.hideMenuColonne();
			}.bind(this)).addEvent('mouseenter',function(){
				chiudiTableMenuColonne.setStyle('text-decoration','none')
			}).addEvent('mouseleave',function(){
				chiudiTableMenuColonne.setStyle('text-decoration','underline')
			})
			

			
			var resetTableMenuColonne = new Element('div',{
				'styles':{
					'padding':3,
					'text-align':'right',
					'cursor':'pointer',
					'float':'left',
					'text-decoration':'underline'
				}
			}).appendText('Reset').addEvent('click',function(){
				i=1
				this.colonneHash.each(function(){				
					Cookie.remove(this.element.getProperty('id')+'col_'+i);
					i++;
				}.bind(this))
				this.hideMenuColonne();
				this.filterToQueryString();

			}.bind(this)).addEvent('mouseenter',function(){
				resetTableMenuColonne.setStyle('text-decoration','none')
			}).addEvent('mouseleave',function(){
				resetTableMenuColonne.setStyle('text-decoration','underline')
			})
			resetTableMenuColonne.injectInside(this.menuColonne)
			chiudiTableMenuColonne.injectInside(this.menuColonne)
		}	
	},
	addFilter:function(filterKey,value){
		this.filterHashKey.set(filterKey,value)
	},
	setFilterToQuery:function(filterKey,value){		
		this.filterHashKey.set(filterKey,value)
		this.page=1;
		this.filterToQueryString();
	},
	removeFilterToQuery:function(filterKey){		
		this.filterHashKey.remove(filterKey)
		this.page=1;
		this.filterToQueryString();
	},
	showMenuColonne:function(){
		this.fxMenuColonne.start(this.linkMenuColonne.getCoordinates().left)
	},
	hideMenuColonne:function(){
		this.fxMenuColonne.start(-300)
	},
	setCookieWidth:function(){
		k=1
		this.colonneHash.each(function(itemColonna){
			 //new Hash.Cookie(this.element.getProperty('id')+'col_'+k, {duration: this.options.durationCookie}).set('width',itemColonna.getCoordinates().width);
			 new Hash.Cookie(this.element.getProperty('id')+'col_'+k, {duration: this.options.durationCookie}).set('width',itemColonna.getStyle('width'));
			k++;
		}.bind(this))		
	},
	setGripPosistion:function(){
		//ricolloco tutti tutti i grip		
		$$('div[id^=gripTable_]').each(function(gripTable){			
			//var th=this.thead.getElement('.'+gripTable.getAttribute('id').split('_')[1])
			var th=this.colonneHash.get(gripTable.getAttribute('id').split('_')[1])			
			th.getCoordinates().width
			gripTable.setStyle('left',Number.toInt(th.getCoordinates().left)+Number.toInt(th.getCoordinates().width)-Number.toInt(gripTable.getStyle('width')))
			
		}.bind(this))
		this.setCookieWidth();
	},
	selectAllFn:function(){		
		this.element.getElements('input[name^=chkbox_]').each(function(chkbox){			
				chkbox.checked=true;	
				chkbox.fireEvent('click')
		}.bind(this))
	},
	deSelectAllFn:function(){		
		this.element.getElements('input[name^=chkbox_]').each(function(chkbox){			
				chkbox.checked=false;
				chkbox.fireEvent('click')				
		}.bind(this))
	},
	setFilterDelete:function(){		
		this.deleteFilter = this.btFilterDelete.selectKey
		this.page=1;
		this.filterToQueryString()
	},
	setFilterSearch:function(){
		this.searchFilter = this.searchInput.getProperty('value');
		this.page=1;
		this.filterToQueryString()
	},
	
	filterToQueryString:function(){		
		var qs ='';		
		var fl ='';		
		var flt ='';		
		if(this.colonna != '')  qs +='&col='+this.colonna;
		if(this.ordinamento != '')  qs +='&ord='+this.ordinamento;	
		if(this.page != '')  qs +='&pag='+this.page;
		if(this.deleteFilter != '')  qs +='&delflt='+this.deleteFilter;
		if(this.searchFilter != '')  qs +='&search='+this.searchFilter;
		if(this.filterHashKey.length !=0){			
			var keyArr = this.filterHashKey.keys()
			var flt='';
			keyArr.each(function(key){
				flt += '&'+key+'='+this.filterHashKey.get(key)				
			}.bind(this))			
		}
		redirectInterface.setUrl(this.options.url+qs+flt)
		redirectInterface.go()
	},
	setPage:function (page){
		this.page = page;
		this.filterToQueryString()
	},
	startActionOnChekedStandard:function(selArray,action,url){
		msgBox.closeMsgBox()
		window.setWindowLoad();
		this.idRecord=''
		selArray.each(function(rc){
			this.idRecord+=rc+';';
		}.bind(this))
		new Ajax(url, {
			method: 'get',
			data: 'op='+action+'&idList='+this.idRecord,
			onFailure:function(){
					msgBox.prompt({
						'testo':'Attenzione:/wrap/Si è verificato un Errore di Sistema/wrap/--------/wrap/Contattare il sistemista.',
						'type':TypeMsgBox.Error,
						'buttonList':[['Chiudi','close']]
					});
			},
			onComplete:function(text,xml){
				var root =XmlRead.getXmlTag(xml,'root');				
				if(XmlRead.getXmlTagValue(XmlRead.getXmlTag(root,'result'))==1) {
					msgBox.prompt({
						'testo':'L\'operazione conclusa/wrap/Numero recordi coinvolti nell\'operazione['+XmlRead.getXmlTagValue(XmlRead.getXmlTag(root,'row'))+'] /wrap/--------/wrap/Clicca su Chiudi per ricaricare la pagina',
						'buttonList':[['Chiudi/Ricarica Pagina',function(){
								this.page=1;
								this.filterToQueryString();
								msgBox.closeMsgBox();
							}.bind(this)]]
						});
				}else{
					msgBox.prompt({
						'testo':'Attenzione:/wrap/Si è verificato un Errore di Sistema/wrap/--------/wrap/Contattare il sistemista.',
						'type':TypeMsgBox.Error,
						'buttonList':[['Chiudi','close']]
					});
				}
				
			}.bind(this)
		}).request();	
	},
	getSelected:function(){		
		var i=[]
		this.element.getElements('input[name^=chkbox_]').each(function(chkbox){
			if(chkbox.getProperty('checked')){
				i.push(chkbox.getProperty('value'));
			}
		})
		return i;
	},
	hideColumn:function(nColonna,setAutoNext){	
		this.colonneHash.get(nColonna).nascondi();		
		//nascondo il grip della colonna		
		if($chk($('gripTable_col'+(nColonna-1)))) $('gripTable_col'+(nColonna-1)).setStyle('display','none')
		if(setAutoNext){
			//if($chk(this.colonneHash.get(Number.toInt(nColonna)+1))) this.colonneHash.get(Number.toInt(nColonna)+1).setStyle('width','auto');		
			for(i=1;i<this.colonneHash.length;i++){				
				if(!this.colonneHash.get(i).hasClass('fixed') && this.colonneHash.get(i).getStyle('display') !='none') {
					this.colonneHash.get(i).setStyle('width','auto')
					//alert(this.colonneHash.get(i).id)
					break;
				}
			}
		}
		this.tbody.getElements('tr').each(function(itemTr){
			itemTr.getElements('td')[Number.toInt(nColonna)-1].nascondi();
		})
		
		
		this.setGripPosistion();
		
	},
	showColumn:function(nColonna){
		if(!window.ie){
			this.colonneHash.get(nColonna).setStyle('display','table-cell');
			//mostro il grip della colonna
			if($chk($('gripTable_col'+(nColonna-1)))) $('gripTable_col'+(nColonna-1)).setStyle('display','block')
			
			this.tbody.getElements('tr').each(function(itemTr){
				itemTr.getElements('td')[Number.toInt(nColonna)-1].setStyle('display','table-cell');
			})
		}else{
			this.colonneHash.get(nColonna).setStyle('display','block');
			
			//mostro il grip della colonna
			if($chk($('gripTable_col'+(nColonna-1)))) $('gripTable_col'+(nColonna-1)).setStyle('display','block')
			
			this.tbody.getElements('tr').each(function(itemTr){
				itemTr.getElements('td')[Number.toInt(nColonna)-1].setStyle('display','block');;
			})
		}
		this.setGripPosistion();
	}
});

Element.extend({
	setCustomCheckBox:function(options){
		this.options = $merge({
			'height': 18,
			'width': 18,
			'offset': '-18px',
			'image': 'image/list/checkboxSelect.gif'
		}, options);
		
		this.element = this
				
		this.element.nascondi();
		this.sub = new Element('div',
			{
			'styles':{
				'cursor':'pointer',
				'height':this.options.height,
				'width':this.options.width,
				'background-image':'url('+this.options.image+')',
				'background-repeat':'no-repeat',
				'background-position':'0px 0px'
				
			}
		});
		
		if(this.element.checked)  this.sub.setStyle('background-position','0px '+this.options.offset)
		this.sub.addEvent('click',function(){			
			if(this.element.checked){
				this.element.checked = false;
				this.sub.setStyle('background-position','0px 0px')
				this.element.fireEvent('click')
			}else{
				this.element.checked = true;
				this.sub.setStyle('background-position','0px '+this.options.offset)
				this.element.fireEvent('click')
			}
		}.bind(this))
		this.element.addEvent('click',function(){
			if(this.element.checked){
				this.sub.setStyle('background-position','0px '+this.options.offset)
			}else{
				this.sub.setStyle('background-position','0px 0px')
			}
		}.bind(this))
		this.sub.injectAfter(this.element)
	}
})



FormUI=  new Class({
	initialize: function(element,options){
		this.options = $merge({
			'btActionBack': 'btActionBack',
			'btActionSave': 'btActionSave',
			'modifyMode': false,
			'ajaxUrl': ''
		}, options);
		this.tipsClass= new TipsUI();
		this.scroll = new Fx.Scroll(window, {
			wait: false,
			offset: {'x': -250, 'y': 0},
			duration: 250
		});
		
		this.elementBackAction = $(this.options.btActionBack)	
		this.btActionSave = $(this.options.btActionSave)
		this.changed=false;
		this.testValue='';
		($chk($(element))) ? this.element = $(element) : alert('Classe FormUI: elemento form non trovato');
		//tabIndex
		var tabindex=1;
		this.element.getElements('input').each(function(itemInputText){
			itemInputText.setAttribute('tabindex',tabindex)
			tabindex++;
		})
		this.btActionSave.setAttribute('tabindex',tabindex)
		
		if(this.element.getTag().toUpperCase() != 'FORM') alert('l\'elemento non è un form HTML')
		//over input del modulo
		this.element.getElements('input[class^=input]').each(function(itemInput){
			itemInput.addEvent('focus',function(){
				this.addClass('hover')
				this.focus();
			})
			itemInput.addEvent('blur',function(){
				this.removeClass('hover')
			})
			
			itemInput.addEvent('keydown',function(){			
				this.testValue=itemInput.getProperty('value')
			}.bind(this))
			itemInput.addEvent('keyup',function(){			
				if(this.testValue !=itemInput.getProperty('value')){
					this.changed =true;
				}
			}.bind(this))
		}.bind(this))
		
		this.element.getElements('input[class^=buttonForm]').each(function(itemInput){
			itemInput.addEvent('mouseenter',function(){
				this.addClass('hover')
			})
			itemInput.addEvent('mouseleave',function(){
				this.removeClass('hover')
			})
		})
// yugyn
		if(this.element.getElement('input[type=text]')) {		
			this.element.getElement('input[type=text]').fireEvent('focus');	
		} else {
			if(this.element.getElement('input[type=password]')) {		
				this.element.getElement('input[type=password]').fireEvent('focus');	
			}
		}
//		this.element.getElement('input[type=text]').fireEvent('focus');	
// end yugyn
		//test tasto indietro
		if($chk(this.elementBackAction)){
			this.elementBackAction.addEvent('click',function(event){
				var event= new Event(event);
				if(this.changed){
					event.stop();				
					msgBox.prompt({
						'testo':'Attenzione:/wrap/Non è ancora stato effettuato il salvataggio!/wrap/*******/wrap/Continuando si perderanno le modifiche/wrap/Continuare?',
						'type':TypeMsgBox.Question,
						'buttonList':[['Continua',function(){
							redirectInterface.setUrl(this.elementBackAction.getProperty('href'))
							redirectInterface.go();
						}.bind(this)],['Annulla','close']]
					});
				}			
			}.bind(this))
		}

		this.initRequiredField();
	},
	initRequiredField:function(){
		this.requiredField =$$('input.required');
		this.requiredField.each(function(field){
			field.setStyles({
				'background-image':'url(image/asterisco.png)',
				'background-repeat':'no-repeat',
				'background-position':'right top',
				'width':Number.toInt(field.getStyle('width'))-8,
				'padding-right':'8px'
			})
		})
	},
	alertInput:function(field, testo){
		this.tipsClass.prompt(field,{'testo':testo,'duration':200,'position':'TR','distance':2})
		field.focus();			
// YUGYN
//		field.value = testo;
//		field.select();
		this.scroll.toElement(field)
	},
	postForm:function(msg){		
		this.tipsClass.hide();
		//faccio prima il check dei campi obbligatori
		for(i=0;i<this.requiredField.length;i++) {
			if(this.requiredField[i].form == this.element) {		//YUGYN
				if(String.trim(this.requiredField[i].getProperty('value'))=='') {				
					this.alertInput(this.requiredField[i], msg);
					return;
				}
			}
		}
		if($chk(this.options.ajaxUrl)){
		
			new Ajax(this.options.ajaxUrl, {
				method: 'post',
				data: this.element,
				onRequest :function(){window.lockWindow({'load':true})},
				onComplete:function(text,xml){				
					window.unlockWindowLoad();
					if(XmlRead.getXmlTagValue(XmlRead.getXmlTag(XmlRead.getXmlTag(xml,'root'),'result'))=="1"){					
							msgBox.prompt({
								'testo':'Documento salvato correttamente.',
								'buttonList':[['Torna alla lista',
									function(){																	
										redirectInterface.setUrl(this.elementBackAction.getProperty('href'));
										redirectInterface.go();
									}.bind(this)]]
							});
						
					}else{
						msgBox.prompt({
							'testo':'ATTENZIONE:/wrap/Si è verificato un\'errore durante il salvataggio',
							'type':TypeMsgBox.Error
						});
					}				
				}.bind(this)
			}).request();
		}else{					
			this.element.submit()
		}
	},
	setModifyMode:function(mode){
		this.options.modifyMode=mode;
	},
	getModifyMode:function(){
		return this.options.modifyMode;
	}
})

/*REDIRECT due classi la seconda è obsoleta*/
redirectInterface = new Abstract({	
	setUrl:function(url){
		this.url=url;
	},
	go:function(options){
		this.options = $merge({
			'delay': 1
		}, options);		
		this.changeUrl.create({'delay':this.options.delay}).call()
		
	},
	changeUrl:function(){
		window.location.href=redirectInterface.url
	}
})

//custom select
SelectCustom = new Class({
	initialize:function(element,options){
		this.options = $merge({
			'onChange': Class.empty
		}, options);
	
		if($chk($(element))) this.element = $(element)
		//incapsulo
		this.incapsule = new Element('span',{'styles':{
			'position':'relative',
			'padding':'0px !important',
			'margin':'0px !important'
		}})
		this.incapsule.injectBefore(this.element)
		this.incapsule.adopt(this.element)
		
		//pulsante di select
		this.seleziona = new Element('img',{'styles':{			
						'cursor':'pointer',
						'position':'relative',
						'left':-18
		}});
		if(window.gecko ) this.seleziona.setStyle('top',3)
		this.seleziona.setProperty('src','image/list/select.gif')
		
		this.closeDelay;
		this.selectKey = null;
		this.itemHash = new Hash();
		this.element.setStyle('margin',0)
		this.element.setStyle('color','black')
		this.element.setProperty('readonly',true)
		//window.addInWindow(this.seleziona)
		//this.element.computedPosition(this.seleziona,{'position':'RC','distance':-this.element.getCoordinates().height})
		
		this.seleziona.injectAfter(this.element)
		
		//creo il menu
		this.menu = new Element('div',{'styles':{
			'position':'absolute',
			'border':'1px solid #bbb',
			'background-color':'#fafafa',
			'display':'none',
			'width':this.element.getCoordinates().width-2,
			'left':0,
			'z-index':2
		}})
		if(window.gecko){
			this.menu.setStyle('top',this.element.getCoordinates().height-3)
		}else{
			this.menu.setStyle('top',this.element.getCoordinates().height)
		}
		
		this.seleziona.addEvent('click',function(){			
			this.show()			 
		}.bind(this))
		
		this.menu.addEvent('mouseleave',function(){
			 var fn = this.hide.create({'delay':400,'bind':this})
			 this.closeDelay=  fn();
		}.bind(this))
		this.menu.addEvent('mouseenter',function(){		
			$clear(this.closeDelay)
		}.bind(this))
		
		this.menu.injectAfter(this.element)
		
	},
	addItem:function(alias,key){
		this.itemHash.set(key,alias)		
		var item = new Element('div',{'styles':{
			'font-weight':'bold',
			'line-height':16,
			'padding':'0px 3px',
			'color':'black',
			'cursor':'pointer'
		}});
		item.appendText(alias)
		item.injectInside(this.menu)
		item.addEvent('mouseenter',function(){
			item.setStyle('background-color','#E1EBED')
		})
		item.addEvent('mouseleave',function(){
			item.setStyle('background-color','#fafafa')
		})
		item.addEvent('click',function(){
			this.selectKey = key			
			this.element.setProperty('value',alias)
			this.hide();
			this.options.onChange.create().call()
		}.bind(this))
	},
	show:function(){
		this.menu.setStyle('display','block')
		 var fn = this.hide.create({'delay':1000,'bind':this})
		this.closeDelay=  fn();
	},
	hide:function(){
		this.menu.setStyle('display','none')
	},
	setKey:function(key){
		this.selectKey =key;
		this.element.setProperty('value',this.itemHash.get(key))
	},
	setKeyDefault:function(key){
		if(this.selectKey ==null || this.selectKey == ''){
			this.selectKey =key;
			this.element.setProperty('value',this.itemHash.get(key))
		}
	}
})


//SelectSerchUI
SelectSerchUI = new Class({
	initialize: function(element,options){
		this.options = $merge({
			'height': 240,
			'classe': 'selecUi',
			'onSelect':Class.empty
		}, options);
		
		this.id='selectUi'+$random(1,1000);
		this.element = $(element)
		//incapsulo
		this.incapsule = new Element('span',{'styles':{
			'position':'relative',			
			'padding':'0px !important',
			'margin':'0px !important'
		}})
		this.incapsule.injectBefore(this.element)
		this.incapsule.adopt(this.element)
		
		//creo il field per il codice
		this.fieldUpdate = new Element('input');
		this.fieldUpdate.setAttribute('name',this.element.getAttribute('name'))
		this.fieldUpdate.setAttribute('type','hidden')
		this.element.removeAttribute('name');
		this.fieldUpdate.injectAfter(this.element);
				
		
		//validazione 
		this.valid = false;
		//aggancio l'evento show
		this.coord = this.element.getCoordinates();
		//creo il div da agganciare 
		this.listItem = new Element('div',{
			'styles':{				
				'position':'absolute',				
				'z-index':10000,
				'left':0+Number.toInt(this.element.getStyle('margin-left')),
				'width':this.coord.width-2
			},
			'id':this.id,
			'class':this.options.classe
		})
		
		if(window.ie){
			this.listItem.setStyle('top',this.element.getCoordinates().height+1)
		}else{
			this.listItem.setStyle('top',this.element.getCoordinates().height-3)
		}
		//fx
		this.fx = new Fx.Style(this.listItem, 'opacity',{duration:150}).set(0);
		//scroll
		this.scroll = new Fx.Scroll(this.listItem, {
			wait: false,
			duration: 250
		});
		
		//hash degli item
		
		this.itemHash =new Hash();
		
		this.element.addEvent('blur',function(){
			this.hide.create({'delay':100,'bind':this}).call();
		}.bind(this))
		
		this.element.addEvent('click',function(){
			this.element.select()
		}.bind(this))
		
		//intercetto i tasti
		this.element.addEvent('keyup',function(event){
			if(this.element.isReadOnly()) return
			var event = new Event(event);
			switch(event.key){
				case 'down':
					var sel = this.listItem.getElement('.over');
					if(!$chk(sel)){
						this.show();
						this.listItem.getFirst().addClass('over')
						this.updateKey(this.itemHash.get(this.listItem.getFirst().getProperty('id'))[0])
						this.element.setProperty('value',this.itemHash.get(this.listItem.getFirst().getProperty('id'))[1]);
						this.element.select()
					}else{
						if($chk(sel.getNext())){
							if(this.isVisibile()){
								sel.getNext().addClass('over')
								this.element.setProperty('value',this.itemHash.get(sel.getNext().getProperty('id'))[1]);
								this.element.select()
								this.updateKey(this.itemHash.get(sel.getNext().getProperty('id'))[0])
								sel.removeClass('over');
								this.scroll.toElement(sel.getNext())
							}
						}
					}
					
					
				break;	
				case 'up':
					var sel = this.listItem.getElement('.over');
					if($chk(sel)){
						if($chk(sel.getPrevious())){
							if(this.isVisibile()){
								sel.getPrevious().addClass('over')
								this.element.setProperty('value',this.itemHash.get(sel.getPrevious().getProperty('id'))[1]);
								this.element.select()
								this.updateKey(this.itemHash.get(sel.getPrevious().getProperty('id'))[0])
								sel.removeClass('over')
								this.scroll.toElement(sel.getPrevious())
							}
						}
					}
				break;	
				case 'enter':
					var sel = this.listItem.getElement('.over');
					if($chk(sel)){
						this.element.setProperty('value',this.itemHash.get(sel.getProperty('id'))[1]);
						this.hide();
						this.options.onSelect.call();						
						this.element.select()
					}
				break;	
				default:
					if(!this.isValid()) this.updateKey('')
					this.show();
				break;
			}
		}.bind(this));

	},
	show:function(){				
		if(!$chk($(this.id))) this.listItem.injectInside(this.incapsule)		
		this.clean();
		this.build();		
		if(this.listItem.getStyle('opacity') != 1) this.fx.start(1)
		
	},
	isVisibile:function(){
		return (this.listItem.getStyle('opacity')==0) ? false : true;
	},
	build:function(){
		
		var i=0;
		this.itemHash.each(function(itemHash){
			if(itemHash[1].toLowerCase().contains(this.element.value.toLowerCase()) || itemHash[0].toLowerCase().contains(this.element.value.toLowerCase())){
			//conto gli oggetti
			i++;
			/***************************/
				var item = new Element('div',{
					'styles':{
						'cursor':'pointer',
						'position':'relative'
					},
					id:itemHash[0]
				});
				
				item.addEvent('mousemove',function(){
					if($chk(this.listItem.getElement('.over'))) this.listItem.getElement('.over').removeClass('over');			
					item.addClass('over')
				}.bind(this));
				item.addEvent('mouseleave',function(){
					item.removeClass('over')
				});
				item.addEvent('click',function(event){
					this.element.setProperty('value',this.itemHash.get(this.listItem.getElement('.over').getProperty('id'))[1]);
					this.updateKey(this.itemHash.get(this.listItem.getElement('.over').getProperty('id'))[0])
					this.element.focus();
					this.hide();
					this.options.onSelect.call();
					this.element.select()
				}.bind(this));
				
				pos = itemHash[1].toLowerCase().indexOf(this.element.value.toLowerCase())
				if(pos>=0){
					ext = itemHash[1].substr(pos,this.element.value.length)
					right =itemHash[1].substr(pos+this.element.value.length,itemHash[1].length)
					left =itemHash[1].substr(0,pos)
					item.innerHTML = left+'<b>'+ext+'</b>'+right;
				}else{					
					item.innerHTML = itemHash[1];
				}
				
				//div kiave
				var itemKey = new Element('span',{
					'styles':{
						'position':'absolute',
						'padding':'1px 2px',
						'right':4,
						'top':0
					}
				});
				
				pos = itemHash[0].toLowerCase().indexOf(this.element.value.toLowerCase())
				if(pos>=0){
					ext = itemHash[0].substr(pos,this.element.value.length)
					right =itemHash[0].substr(pos+this.element.value.length,itemHash[0].length)
					left =itemHash[0].substr(0,pos)
					itemKey.innerHTML = left+'<b>'+ext+'</b>'+right;
					
				}else{										
					itemKey.innerHTML=itemHash[0];
				}
				
							
				itemKey.injectInside(item)
				item.injectInside(this.listItem)
				
			/******************************/	
			}
		}.bind(this))				
		//se sono + di 10 imposto l'altezza massima
		if(i>10){			
			this.listItem.setStyle('height',this.options.height)
			this.listItem.setStyle('overflow-y','scroll')
		}else{
			this.listItem.setStyle('height','auto')
			this.listItem.setStyle('overflow-y','hidden')
		}
	},
	addItem:function(value,key){
		this.itemHash.set(key,[key,value])
		
	},
	clean:function(){
		this.listItem.getElements('div').each(function(item){
			item.remove();
		})
	},
	hide:function(){
		this.fx.start(0)
	},
	updateKey:function(value){
		if($chk(this.fieldUpdate)) this.fieldUpdate.setProperty('value',value)		
	},
	initValue:function(key){
		this.element.setProperty('value',this.itemHash.get(key)[1])
	},
	isValid:function(){
		this.valid=false;
		this.itemHash.values().each(function(item){
			if(item[1]==this.element.getProperty('value')) this.valid=true;
		}.bind(this))
		return this.valid;
	},
	getValue:function(){
		return this.fieldUpdate.getProperty('value')
	}
	

})
var msgBox = new MsgBox();
var Tips = new TipsUI();
