/***************************************************************/
/* COSTANTI						       */
/***************************************************************/

contenuto_height={small:290,big:430}
menu_height={small:168,big:98}
mondo_line_color={over:"#FA6906",out:"#848481"}

var isIE = navigator.appName.indexOf("Microsoft") != -1;

/***************************************************************/
/* FUNZIONI						       */
/***************************************************************/

Fx.mzStyle = Fx.Style.extend({

	increase: function(){
		if(this.element.setStyle) this.element.setStyle(this.property, this.css.getValue(this.now, this.options.unit, this.property));
	}
});

showthis=function(obj){
	new Fx.mzStyle(obj, 'opacity',{duration:500,transition:Fx.Transitions.linear}).start(0,1);
}

trythis=function(obj,fn,param){
	if(eval(obj)){
		eval(obj)[fn](param)
	}else{
		window.setTimeout("trythis('"+obj+"','"+fn+"','"+param+"')", 1000);
	}
}

createtips=function(elements){

	return new Tips(elements, {
			initialize:function(){
				this.fx = new Fx.Style(this.toolTip, 'opacity', {duration: 500, wait: false}).set(0);
			},
			onShow: function(toolTip) {
				this.fx.start(1);
			},
			onHide: function(toolTip) {
				this.fx.start(0);
			}
		});
}

listselection=function(element,ul,cls){
	var list = (ul) ? ul : [element.getParent().getParent()]
	var sel = (cls) ? cls : "selected"
	list.each(function(u){u.getChildren().each(function(el){el.getElement('a').removeClass(sel);})});
	element.addClass(sel)
}

getFlashMovie=function(movieName) {
  return (isIE) ? $(movieName) : $(movieName+'_fx');
  //return (isIE) ? $(movieName) : null;
}

getFlashMovieParent=function(movieName) {
  var isIE = navigator.appName.indexOf("Microsoft") != -1;
  //if (isIE) {

	var objects = document.getElementsByTagName("OBJECT");
	for (var i=0; i < objects.length; i++) {
		if(objects[i]["id"]==movieName){
		  	return objects[i]["parentElement"];
		}
	}
	
  //}else{
  //	return $(movieName+'_fx')
  //}
}

delFlashMovie=function(movieName) {
  var isIE = navigator.appName.indexOf("Microsoft") != -1;
  if (isIE){

   	var arr = document.all.tags("object");
   	if (arr && arr.length) {
   		for (var i=arr.length-1; 0<=i; i--) {
   			if(arr[i]["id"]==movieName){
				for (var x in arr[i]) {
					if (typeof arr[i][x] == 'function') {
						arr[i][x] = null;
					}
				}
	   			arr[i].removeNode(true);
   			}
   		}
   	}
  
  }else{
	getFlashMovie(movieName).remove();
  }
}

clearFlashMovie=function(){

		if(getFlashMovie("flash_content")!=undefined && getFlashMovie("flash_content")!=null){
			delFlashMovie("flash_content")
		}

		if(getFlashMovie("flash_video")!=undefined && getFlashMovie("flash_video")!=null){
			delFlashMovie("flash_video")
		}

		if(getFlashMovie("flash_subcontent")!=undefined && getFlashMovie("flash_subcontent")!=null){
			delFlashMovie("flash_subcontent")
		}

}


if(isIE) window.attachEvent("onbeforeunload",clearFlashMovie);

/***************************************************************/
/* OGGETTI						       */
/***************************************************************/

var clsHistory=new Class({

	initialize: function(name,init){
	
		this.obj = {};		
		this.queue = {};
		this.name = name;
		this.init = (init) ? init : '';
	
		this.history = HistoryManager.register(
			this.name,
			[this.init],
			function(values) {
				result = ('],'+values[0]+',[').split('],[')
				this.doit(result.slice(1,-1));
			}.bind(this),
			function(values) {
				return [this.name+'(', values.join(','), ')'].join('');
			}.bind(this),
			this.name+'\\(([^)]*)\\)'
		);

	},
	
	register: function(key,obj){

		this.obj[key]=obj;
		return{
			setValues: function(values) {
				return this.setValues(key, values);
			}.bind(this)
		};
	
	},
	
	setValues: function(key,values){
	
		this.queue[key]=values;
		
	},
	
	flush: function(){
	
		var result=Array()
	
		for(obj in this.queue){
		
			result.push("["+obj+"|"+this.queue[obj].join('|')+"]")	
		}
		
		//this.queue={};
		
		this.history.setValues(result);
	
	},

	doit: function(params){
	
		var row=Array();
		
		for(var i=0;i<params.length;i++){
		
			row=params[i].split('|');		
		
			this.obj[row[0]].doit(row[1],row.slice(2));
		
		
		}
	
	}
	

});

var clsHistoryOff = new Class({

    initialize: function(name, init) {

        this.obj = {};
        this.queue = {};
        this.name = name;
        this.init = (init) ? init : '';

        this.history = HistoryManager.register(
			this.name,
			[this.init],
			function(values) {
			    result = ('],' + values[0] + ',[').split('],[')
			    this.doit(result.slice(1, -1));
			} .bind(this),
			function(values) {
			    return [this.name + '(', values.join(','), ')'].join('');
			} .bind(this),
			this.name + '\\(([^)]*)\\)'
		);

    },

    register: function(key, obj) {

        this.obj[key] = obj;
        return {
            setValues: function(values) {
                return this.setValues(key, values);
            } .bind(this)
        };

    },

    setValues: function(key, values) {

        this.queue[key] = values;

    },

    flush: function() {
    },

    doit: function(params) {
    var row = Array();

    for (var i = 0; i < params.length; i++) {

        row = params[i].split('|');

        this.obj[row[0]].doit(row[1], row.slice(2));


    }
}


});

var clsLoader=new Class({

	initialize: function(hst,init_function){
	
		this.contenuto = $('contenuto');
		this.wrapper = $('wrappercontenuto');
		this.menu = $('menu');
		this.init=(init_function) ? init_function.bind(this) : function(){};
	
		this.history = (hst) ? hst.register('loader',this) : null;
		
		this.ajaxobj=null;

	},
	
	doit: function(action,params){

		switch(action){
		case "init":
			this.init();
		break;
		case "content":
			this.open_content(params[0],params[1]);
		break;
		}
	
	},
	
	load_content: function(link_page,layer_page,complete_func){
	
		this.ajaxobj=null;

		this.ajaxobj=new Ajax(unescape(link_page), {
			method: 'get',
			evalScripts: true,
			update: layer_page,
			onComplete: (complete_func==undefined) ? function(){} : complete_func
		}).request();
	
	},

	
	open_page: function(link_page,size,opacity){
	
		opacity = (opacity==undefined || opacity==null) ? 1 : opacity;

		if(this.wrapper.getStyle('height').toInt() != contenuto_height[size]){
			new Fx.Style(this.menu, 'height', {duration: 500}).start(menu_height[size]);
			new Fx.Style(this.wrapper, 'height', {duration: 500, onComplete:function(){this.open_page(link_page,size,opacity);}.bind(this)}).start(contenuto_height[size]);
			return
		}

		if(isIE) {
			//alert("go");
			clearFlashMovie();}

		this.contenuto.empty().setHTML("<div><img src='00_files/img/loading.gif'></div>");
		this.contenuto.setOpacity(opacity);
		this.load_content(link_page,this.contenuto)

	},

	open_content: function(link_page,size){

		size = (size==undefined || size==null) ? 'big' : size;

		if(this.history) this.history.setValues(["content",escape(link_page),size])
		
		if(isIE && getFlashMovie("flash_content")) {
			if(getFlashMovie("flash_content").close_content){
				getFlashMovie("flash_content").close_content();
			}
		}
		
		new Fx.Style(this.contenuto, 'opacity',{duration: 500, onComplete:function(){this.open_page(link_page,size);}.bind(this)}).start(1,0);			

	}

});


var clsSubLoader=new Class({

	initialize: function(hst,init_function){
	
		this.history = (hst) ? hst.register('loader',this) : null;
		this.init=(init_function) ? init_function.bind(this) : function(){};

	},
	
	doit: function(action,params){

		switch(action){
		case "init":
			this.init();
		break;
		case "content":
			this.open_content(params[0],params[1]);
		break;
		}
	
	},
	
	load_content: function(link_page,layer_page,complete_func){

		new Ajax(unescape(link_page), {
			method: 'get',
			evalScripts: true,
			update: layer_page,
			onComplete: (complete_func==undefined) ? function(){} : complete_func
		}).request();
	
	},

	
	open_page: function(link_page,target,opacity){
		
		opacity = (opacity==undefined || opacity==null) ? 1 : opacity;

		if(isIE){
		if(getFlashMovie("flash_subcontent")!=undefined && getFlashMovie("flash_subcontent")!=null){
			if(getFlashMovieParent("flash_subcontent")==$(target)) {
				delFlashMovie("flash_subcontent")
			}
		}
		}
		$(target).empty().setHTML("<div><img src='00_files/img/loading.gif'></div>");
		$(target).setOpacity(opacity);
		this.load_content(link_page,$(target))

	},

	open_content: function(link_page,target){

		if(this.history) this.history.setValues(["content",escape(link_page),target])
		
		//if(getFlashMovie("flash_subcontent")!=undefined && getFlashMovie("flash_subcontent")!=null){
		
		//	if(getFlashMovieParent("flash_subcontent")==$(target)){
		//		getFlashMovie("flash_subcontent").close_content(link_page,target);
		//		return;
		//	}
			
		//}
	
		new Fx.Style($(target), 'opacity',{duration: 500, onComplete:function(){this.open_page(link_page,target);}.bind(this)}).start(1,0);			
	
	}

});

var clsSlider=new Class({

	options: {
		hst:false,
		init_function:false,
		usecmdGallery:true,
		minHeight:0,
		maxHeight:250,
		layerTransition:Fx.Transitions.linear,
		layerSpeed:500
	}, 

	initialize: function(objname,objs,options){

		this.setOptions(options);
	
		this.objname=objname;
		this.objs=objs;
		this.history = (this.options.hst) ? this.options.hst.register(this.objname,this) : null;
		this.init=(this.options.init_function) ? this.options.init_function.bind(this) : function(){};

	},
	
	doit: function(action,params){

		switch(action){
		case "init":
			this.init();
		break;
		case "hide":
			this.hide();
		break;
		case "show":
			this.show();
		break;
		}
	
	},
	
	show: function(){
	
		var eseguito=false;

		this.objs.each(function(el){

			if($(el)) {
				
				eseguito=true;
				new Fx.Style($(el), 'height' ,{duration: this.options.layerSpeed,transition:this.options.layerTransition}).start(this.options.maxHeight);
			
			}	
		
		}.bind(this))

		if(this.history && eseguito) this.history.setValues(["show"]);

	},

	hide: function(){

		var eseguito=false;

		this.objs.each(function(el){

			if($(el)) {

				eseguito=true;
				new Fx.Style($(el), 'height' ,{duration: this.options.layerSpeed,transition:this.options.layerTransition}).start(this.options.minHeight);
			
			}
		
		
		}.bind(this))

		if(this.history && eseguito) this.history.setValues(["hide"])
		
	}
	
});

clsSlider.implement(new Options);


var clsMenu=new Class({

	initialize: function(div_class,hst,tree,menu){
	
		this.div_class = div_class;
		this.starttree = tree;
		this.startmenu = (menu) ? menu : new Array();
		this.selectedtree = tree;
		this.selectedmenu = (menu) ? menu : new Array();		
		this.rolledmenu = '';
		this.menu_fxslide = {};
		this.menu_fxalpha = {};
		this.menu_fxline = {};
		this.menu_busy = 0;

		$$("div."+this.div_class).each(function(el){
		
			el.addEvent("mouseleave",function(event){this.out_menu("azzera");}.bind(this));
			
 			this.menu_fxslide[el.id] = new Fx.Slide(el, {duration: 500, mode:'horizontal', onComplete:function(){if(this.menu_fxslide[el.id].wrapper.getStyle('width').toInt()!=0){this.menu_busy--;}}.bind(this)});
			this.menu_fxalpha[el.id] = new Fx.Style(el, 'opacity', {duration: 500});
		 			
 			if(!this.selectedtree.split(",").contains(el.className.split(" ")[1])){
 				this.menu_fxslide[el.id].hide()
 				this.menu_fxalpha[el.id].set(0)
 			}
 			
		}.bind(this));

		$$('div.riga').each(function(el){
			this.menu_fxline[el.id] = new Fx.Style(el, 'opacity', {duration: 500});
		}.bind(this));

		this.history = (hst) ? hst.register('menu',this) : null;

	},
	
	doit: function(action,params){

		switch(action){
		case "init":
			this.selectedtree=this.starttree;
			this.selectedmenu=this.startmenu;
			this.selectedmenu.each(function(item,index){this.select_voice(index,item)}.bind(this));
			this.set_menu(this.selectedtree);
		break;
		case "sel":
			this.select_menu(params[0],params[1],params[2]);
		break;
		case "res":
			this.reset_menu(params[0],params[1]);
		break;
		}
	
	},
	
	reset_menu: function(list,menu){
		
		this.selectedtree = list;
		this.select_voice(0)
		this.selectedmenu = (menu) ? menu : new Array();		
		this.rolledmenu = '';
		this.selectedmenu.each(function(item,index){this.select_voice(index,item)}.bind(this));
		this.set_menu(list);
		if(this.history) this.history.setValues(["res",list,menu])
		
	},

	set_menu: function(list){
		
		for(obj in this.menu_fxslide){
			this.menu_fxslide[obj].stop();
			this.menu_fxalpha[obj].stop();
		}

		for(obj in this.menu_fxline){
			this.menu_fxline[obj].stop();
		}
		
		this.menu_busy = $$(list.split(",").map(function(item,index){return "div."+item}).toString()).length;

		this.close_voices(list);
		this.open_voices(list);
		
	},
	
	select_menu: function(list,level,voice){
		
		if(!this.menu_busy){
			this.selectedtree=list;
			this.select_voice(list.split(",").indexOf(level),voice)
			this.set_menu(list);			
			if(this.history) this.history.setValues(["sel",list,level,voice])
		}

	},
	
	over_menu: function(list){
	
		this.rolledmenu=list;

	},

	out_menu: function(first){


		if(first=="azzera"){
			this.rolledmenu='';
			window.setTimeout(this.out_menu.bind(this), 2000);
		}else{
			if(!this.menu_busy && (this.rolledmenu=='' || this.selectedtree.substr(0,this.rolledmenu.length)+','==this.rolledmenu+',')) this.set_menu(this.selectedtree);			
			//if((this.rolledmenu=='' || this.selectedtree.substr(0,this.rolledmenu.length)+','==this.rolledmenu+',')) this.set_menu(this.selectedtree);			
		}

	},

	select_voice: function(level,voice){
		
		for(var k=level;k<this.selectedmenu.length;k++){
			if(this.selectedmenu[k]) $(this.selectedmenu[k]).getElement('a').removeClass('selected');
		}
		
		this.selectedmenu[level]=voice;
		if(voice) $(voice).getElement('a').addClass('selected');
		
	},

	close_voices: function(open_menu){

		var menus=open_menu.split(",");
	
		this.alpha_lines(menus,0);

		$$("div."+this.div_class).each(function(el){

		 	if(!this.selectedtree.split(',').contains(el.getProperty("class").substr(el.getProperty("class").indexOf(" ")+1)) && !menus.contains(el.getProperty("class").substr(el.getProperty("class").indexOf(" ")+1))){

		 		this.menu_fxslide[el.id].slideOut();
				this.menu_fxalpha[el.id].start(0);	 		
			}	 			
	
		}.bind(this))

	},

	open_voices: function(open_menu){

		var menus=open_menu.split(",");
	
		this.alpha_lines(menus,1);
		
		menus.each(function(item, index){
		
			$$('div.'+item).each(function(el){
			
				this.menu_fxslide[el.id].slideIn();
		 		if(el.getStyle('opacity').toInt()!=1){
		 			this.menu_fxalpha[el.id].start(1);
		 		}
			}.bind(this))

		}.bind(this));
	
	},
	
	alpha_lines: function(menus,alpha){
	
		$$('div.riga').each(function(el){
			
			var selectedline=1;
			
			menus.each(function(item, index){
				if(!el.hasClass('R'+item) || menus.length==1) selectedline=0;
			});
			
			if(!Math.abs(alpha-selectedline)) this.menu_fxline[el.id].start(alpha);
			
		}.bind(this));
			
	}

});

var clsMenuCucine=new Class({

	initialize: function(obj_classes,hst,cucina,menu){
	
		this.obj_classes = obj_classes;
		this.startsel = [cucina,menu];
		this.selectedcucina = cucina;		
		this.selectedmenu = menu;		
		this.menu_busy = 0;
		this.menu_animate = {};

		for(obj in this.obj_classes){
		
			this.menu_animate[obj] = new Fx.Elements($$(obj),{wait: false, duration: 200, transition: Fx.Transitions.quadOut})
				
		}
		

		this.history = (hst) ? hst.register('menucucine',this) : null;

	},
	
	doit: function(action,params){

		switch(action){
		case "init":
			this.selectedcucina = this.startsel[0];		
			this.selectedmenu = this.startsel[1];		
			$$('div.mondo_line').each(function(el){
				el.setStyle("border-color",mondo_line_color.out)
			}.bind(this))
			this.set_menu()
		break;
		case "sel":
			this.select_menu(params[0],params[1]);
		break;
		case "res":
			this.reset_menu();
		break;
		}
	
	},
	
	reset_menu: function(){
		
		this.selectedcucina = null;
		this.selectedmenu = null;		
		$$('div.mondo_line').each(function(el){
			el.setStyle("border-color",mondo_line_color.out)
		}.bind(this))
		this.set_menu();
		if(this.history) this.history.setValues(["res"])
		
	},

	set_menu: function(list){
		
		for(obj in this.menu_animate){
			this.menu_animate[obj].stop();
		}

		//this.menu_busy = (list) ? list.split(",").length : 0;

		this.open_voices(list);
		
	},
	
	select_menu: function(voice,menu){
		
		if(!this.menu_busy){

			this.selectedcucina=voice;
			this.selectedmenu=menu;
		
			$$('div.mondo_line').each(function(el){
				if(this.selectedmenu!=el.className.split(" ")[1]){
					el.setStyle("border-color",mondo_line_color.out)
				}else{
					el.setStyle("border-color",mondo_line_color.over)					
				}
			}.bind(this))
			
			this.set_menu();
			if(this.history) this.history.setValues(["sel",escape(voice),menu])
		}

	},
	
	open_voices: function(open_menu){

		var menus=(open_menu) ? open_menu.split(",") : new Array();
	
		for(obj in this.obj_classes){
		
			var objeffect = {}
			
			$$(obj).each(function(el,i){
	 			if(menus.contains(el.id) || this.selectedcucina==el.className.substr(el.className.indexOf(" ")+1) || this.selectedmenu==el.className.substr(el.className.indexOf(" ")+1)){
					objeffect[i]=this.obj_classes[obj].over
				}else{
					objeffect[i]=this.obj_classes[obj].out
				}
			}.bind(this))
			
			this.menu_animate[obj].start(objeffect);
					
		}
		
	}
	
});

/****************************************************************/

function emailCheck (emailStr, lingua) {
/* The following pattern is used to check if the entered e-mail address
   fits the user@domain format.  It also is used to separate the username
   from the domain. */
var emailPat=/^(.+)@(.+)$/
/* The following string represents the pattern for matching all special
   characters.  We don't want to allow special characters in the address. 
   These characters include ( ) < > @ , ; : \ " . [ ]    */
var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
/* The following string represents the range of characters allowed in a 
   username or domainname.  It really states which chars aren't allowed. */
var validChars="\[^\\s" + specialChars + "\]"
/* The following pattern applies if the "user" is a quoted string (in
   which case, there are no rules about which characters are allowed
   and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
   is a legal e-mail address. */
var quotedUser="(\"[^\"]*\")"
/* The following pattern applies for domains that are IP addresses,
   rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
   e-mail address. NOTE: The square brackets are required. */
var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
/* The following string represents an atom (basically a series of
   non-special characters.) */
var atom=validChars + '+'
/* The following string represents one word in the typical username.
   For example, in john.doe@somewhere.com, john and doe are words.
   Basically, a word is either an atom or quoted string. */
var word="(" + atom + "|" + quotedUser + ")"
// The following pattern describes the structure of the user
var userPat=new RegExp("^" + word + "(\\." + word + ")*$")
/* The following pattern describes the structure of a normal symbolic
   domain, as opposed to ipDomainPat, shown above. */
var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")


/* Finally, let's start trying to figure out if the supplied address is
   valid. */

/* Begin with the coarse pattern to simply break up user@domain into
   different pieces that are easy to analyze. */
var matchArray=emailStr.match(emailPat)
if (matchArray==null) {
  /* Too many/few @'s or something; basically, this address doesn't
     even fit the general mould of a valid e-mail address. */
	switch (lingua)
	{
		case "it": alert("Il formato dell'indirizzo Email non è valido.\n(controllare @ e dominio)"); break;
		case "es": alert("El formato de la dirección Email no es válido.\n(controlar @ y dominio)"); break;
		default  : alert("Email address seems incorrect (check @ and .'s)"); break;
	}
 
	return false
}
var user=matchArray[1]
var domain=matchArray[2]

// See if "user" is valid 
if (user.match(userPat)==null) {
    // user is not valid
	switch (lingua)
	{
		case "it": alert("Il formato del nome non è valido.\n(controllare i caratteri prima la @)"); break;
		case "es": alert("El formato del nombre no es válido.\n(controlar los caracteres antes de la @)"); break;
		default  : alert("The domain name doesn't seem to be valid."); break;
	}
    
    return false
}

/* if the e-mail address is at an IP address (as opposed to a symbolic
   host name) make sure the IP address is valid. */
var IPArray=domain.match(ipDomainPat)
if (IPArray!=null) {
    // this is an IP address
	  for (var i=1;i<=4;i++) {
	    if (IPArray[i]>255) {
	        alert("Destination IP address is invalid!")
		return false
	    }
    }
    return true
}

// Domain is symbolic name
var domainArray=domain.match(domainPat)
if (domainArray==null) {
	switch (lingua)
	{
		case "it": alert("Il formato del dominio non è valido.\n(controllare i caratteri dopo la '@')"); break;
		case "es": alert("El formato del dominio no es válido.\n(controlar los caracteres después de la @)"); break;
		default  : alert("The domain name doesn't seem to be valid."); break;
	}

    return false
}

/* domain name seems valid, but now make sure that it ends in a
   three-letter word (like com, edu, gov) or a two-letter word,
   representing country (uk, nl), and that there's a hostname preceding 
   the domain or country. */

/* Now we need to break up the domain to get a count of how many atoms
   it consists of. */
var atomPat=new RegExp(atom,"g")
var domArr=domain.match(atomPat)
var len=domArr.length
if (domArr[domArr.length-1].length<2 || 
    domArr[domArr.length-1].length>3) {
   // the address must end in a two letter or three letter word.
	switch (lingua)
	{
		case "it": alert("Un indirizzo Email deve finire con 3 lettere\ndi dominio o due lettere di nazione."); break;
		case "es": alert("Una dirección Email debe finalizar con 3 letras.\n de dominio o dos letras de nación"); break;
		default  : alert("The address must end in a three-letter domain, or two letter country."); break;
	}
   
   return false
}

// Make sure there's a host name preceding the domain.
if (len<2) {
   var errStr="This address is missing a hostname!"
   alert(errStr)
   return false
}

// If we've gotten this far, everything's valid!
return true;
}