﻿MyForm={
	regex:{
		'_req':/.+/,
		'_name':/[a-zA-Z\' ]+/,
		'_num':/\d/,
		'_cap':/\d{5}/,
		'_pr':/[a-zA-z]{2}/,
		'_email':/^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$/,
		'_iva':/[0-9]/,
		'_codfisc':/[a-zA-Z]{6}[0-9]{2}[a-zA-Z][0-9]{2}[a-zA-Z][0-9]{3}[a-zA-Z]/,
		'_psw':/.+/
	},

	
	controls:function(formName){
		classes = new Array();
		ids = new Array();
		field = new Array();
		all = $$('#'+formName+' ._*');
		for (i=0, l=all.length; i<l; i++){
			ids.push(all[i].id);
			classes.push(all[i].className);
		}
		for (i=0, l=ids.length; i<l; i++){
			var allClasses = classes[i].split(' ');
			allClasses.splice(0,1);
			for(a=0, len=allClasses.length; a<len; a++){
				for (t in MyForm.regex){
					if (t == allClasses[a]){
						var regexTest = MyForm.regex[t];
						var value = $(ids[i]).value;
						var testValue = regexTest.test(value);
						var err = ids[i];
						if (!testValue) {
							$(err).addClassName('inputError');
							field[i] = ids[i].replace(/_/g,' ');
							switch (Common.lang()){
								case 'it': Common.error('Il campo <b>"'+field[i]+'"</b> non sembra corretto.', err); break;
								case 'en': Common.error('The field <b>"'+field[i]+'"</b> doesn&#39;t seem correct.', err); break;
								case 'de': Common.error('Der abgelegte <b>"'+field[i]+'"</b> Name scheint korrekt nicht.', err); break;
								case 'fr': Common.error('Le class&eacute; <b>"'+field[i]+'"</b> ne semble pas correct.', err); break;
								case 'es': Common.error('El archivado <b>"'+field[i]+'"</b> no parece correcto.', err); break;
							};
							return false;
						} else
							$(err).removeClassName('inputError');
					}
				}
			} 
		}
		return true;
	},


	/*compare:function(){
		alert('test');
		for (i=0;i<3;i++){
			var psw[i] = document.getElementsById('product'+i);
		}
			if (psw[0].value != psw[1].value){
				switch (Common.lang()){
					case 'it': Common.error('Le password non corrispondono', psw[1].id); break;
					case 'en': Common.error('The passwords don&#39;t correspond', psw[1].id); break;
					case 'de': Common.error('Die Kennw&ouml;rter entsprechen nicht', psw[1].id); break;
					case 'fr': Common.error('Les mots de passe ne correspondent pas', psw[1].id); break;
					case 'es': Common.error('Las contrase&ntilde;as no corresponden', psw[1].id); break;
				}
				return false;
			} else
				return true;
		}
	},*/

	
	checkbox:function(){
		if ($('accept')){
			if ($('accept').checked==false){
				switch (Common.lang()){
					case 'it': Common.error('Non hai accettato la <b>normativa sulla privacy</b>', 'acccept'); break;
					case 'en': Common.error('You have not accepted the <b>privacy terms</b>', 'acccept'); break;
					case 'de': Common.error('Sie haben die <b>Privatleben-Bezeichnungen</b> nicht akzeptiert', 'acccept'); break;
					case 'fr': Common.error('Vous n&#39;avez pas accept&eacute; les <b>termes de vie priv&eacute;e</b>', 'acccept'); break;
					case 'es': Common.error('Usted no ha aceptado los <b>t&eacute;rminos de intimidad</b>', 'acccept'); break;
				};
				return false;
			}
		}
		return true;
	},
	
	
	privacy_saeco:function(){
		if ($('accept')){
			if ($('accept').checked==false){
					var text = $F('privacy_error')+'<br/><br/><a href="#" id="btn_prosegui" "title="'+$F('privacy_prosegui')+'">'+$F('privacy_prosegui')+'</a><a href="#" id="btn_torna" "title="'+$F('privacy_torna')+'">'+$F('privacy_torna')+'</a><br class="cleaner"/>';
					Common.error(text,'acccept');
					Event.observe('btn_prosegui', 'click', function(event){event.stop(); Btns.send('form_contact');});
					Event.observe('btn_torna', 'click', function(event){event.stop(); MyForm.close_privacy();});
					return false;
			}
		}
		return true;
	},
	close_privacy:function(){
		err = $('error');
		msg = $('err_msg');
		new Effect.Opacity(msg, {to:0.0, from:1.0, duration:0.3, afterFinish:function(){
				new Effect.Appear(err, {to:0.0, from:1.0, duration:0.3, afterFinish:function(){
					err.remove();
					msg.remove();
					/* riappaiono i select */
					var selects = document.getElementsByTagName("select"); 
					for (var i = 0; i < selects.length; i++) { 
						selects[i].style.visibility='visible';
					}
				}});	
			}
		});
		
	},
	
	
	show:function(div){
		var x = $(div).style.display;
		(x == 'none')? new Effect.BlindDown($(div),{duration: 0.5}) : new Effect.BlindUp($(div),{duration: 0.5});
	},
	
	passwords:function(){
		if (document.getElementsByClassName('_psw')){
			var psw = document.getElementsByClassName('_psw');
			if (psw[0].value != psw[1].value){
				switch (Common.lang()){
					case 'it': Common.error('Le password non corrispondono', psw[1].id); break;
					case 'en': Common.error('The passwords don&#39;t correspond', psw[1].id); break;
					case 'de': Common.error('Die Kennw&ouml;rter entsprechen nicht', psw[1].id); break;
					case 'fr': Common.error('Les mots de passe ne correspondent pas', psw[1].id); break;
					case 'es': Common.error('Las contrase&ntilde;as no corresponden', psw[1].id); break;
				}
				return false;
			} else
				return true;
		}
	},
	
	
	nations:function(){
		var nation = $(Common.fieldsID['nazione']).value;
		var province = $('province');
		if (nation == 'IT')
			$(province).style.display='block';
		else
			$(province).style.display='none';
	},
	
	
	reg_as:function(){
		$(Common.fieldsID['cod_fisc']).value='';
		$(Common.fieldsID['rag_soc']).value='';
		$(Common.fieldsID['p_iva']).value='';
		if ($('privato').checked){
			$('reg_privato').style.display='block';
			$('reg_azienda').style.display='none';
			$(Common.fieldsID['cod_fisc']).className='_* _req';
			$(Common.fieldsID['rag_soc']).className='';
			$(Common.fieldsID['p_iva']).className='';
		} else {
			$('reg_privato').style.display='none';
			$('reg_azienda').style.display='block';
			$(Common.fieldsID['cod_fisc']).className='';
			$(Common.fieldsID['rag_soc']).className='_* _req';
			$(Common.fieldsID['p_iva']).className='_* _iva';
		}
	},
	
	default_radio:function(){
		if ($('postVerify').value=='' && $('privato')){
			$('privato').checked=true;
			$(Common.fieldsID['rag_soc']).value='';
			$(Common.fieldsID['p_iva']).value='';
		}
	},
	
	checkDate:function(){
		var d1 = parseInt($F('day_start'));
		var m1 = parseInt($F('month_start'));
		var y1 = parseInt($F('year_start'));
		
		var d2 = parseInt($F('day_end'));
		var m2 = parseInt($F('month_end'));
		var y2 = parseInt($F('year_end'));
		
		console.log(d1,m1,y1,d2,m2,y2);
		
		if (y2>=y1 && m2>=m1 && d2>d1){
			return true;
		}else{
			switch (Common.lang()){
				case 'it': Common.error('Le <b>date</b> sono errate', $('day_start')); break;
				case 'en': Common.error('The <b>dates</b> are incorrect', $('day_start')); break;
				case 'de': Common.error('Le <b>date</b> sono errate', $('day_start')); break;
			}
			return false;
		}
		console.log(checkDate());
	}
	
},



Browse={
	fileType:null,
	match:null,
	invisible:function(divID){
		new Effect.Opacity($(divID),{from: 1.0, to: 0.0, duration: 0});
	},
	error:function(){
		switch (Common.lang()){
			case 'it': Common.error('Il tipo di file che stai cercando di caricare non &egrave; supportato', 'file'); break;
			case 'en': Common.error('The type of file that you want to upload is not supported', 'file'); break;
			case 'de': Common.error('Die Art Akte, die Sie laden wollen, ist nicht unterst&uuml;tzt', 'file'); break;
			case 'fr': Common.error('Le type de dossier que vous voulez t&eacute;l&eacute;charger n&#39;est pas soutenu', 'file'); break;
			case 'es': Common.error('El tipo del archivo que usted quiere cargar no es apoyado', 'file'); break;
		};
	},
	sendValue:function(fileID, destID){
		var exts = $(fileID).accept;
		var allExts = exts.split(',');
		var fileMatch = /([^.]+)$/.exec($F(fileID));
		var fileExt = fileMatch[0];
		if (exts != 'all'){ // check if all extensions are available or not
			for (i=0,l=allExts.length; i<l; i++){
				if (fileExt == allExts[i]){
					$(destID).value=$F(fileID);
					break;
				}else {
					Browse.error();
					$(destID).value='';
					$(fileID).value='';
					break;
				}
			}
		} else {
			var danger = new Array('exe','chm','vbx','ovl','sys','qtx','job','html','pif','crt','hta','inf','ins','isp','jse','jsp','lnk','scr','shb','shs','url','bat','msi','dll','ocx','sh','dmg','vbs','js','php','asp','py','pl','cf','ini');
			for (i=0,l=danger.length; i<l; i++){
				if (fileExt == danger[i]){
					var findError = true;
					break;
				}
			}
			if (findError!=true){
				$(destID).value=$F(fileID);
			}else{
				Browse.error();
				$(destID).value='';
				$(fileID).value='';
			}
		}
	}
},


MyAjax={
	noCache:function(){
		//response.setHeader("Cache-Control", "no-cache");
		//requestHeaders("Cache-Control", "no-cache");
		//response.setHeader("Pragma", "no-cache");
	},

	// controllo se la mail è già presente nel db
	request:function(formName){
		new Ajax.Request(Common.myhost()+'/scripts/controllo.php?email='+$('E-mail').value, {
			method: 'get',
			requestHeaders: {cacheControl:'no-cache'},
			onSuccess: function(transport) {
				if (transport.responseText.match('ok')){
					modulo=$(formName);
					modulo.submit();
				} else {
					$(Common.fieldsID['email']).style.backgroundColor='#e1f6fd';
					switch (Common.lang()){
						case 'it': Common.error('<b>L&#39;e-mail &egrave; gi&agrave; presente, scegline un&#39;altra', $(Common.fieldsID['email'])); break;
						case 'en': Common.error('The <b>E-mail</b> is already in use,<br/>please choose another one', $(Common.fieldsID['email'])); break;
						case 'de': Common.error('Sie haben die <b>Privatleben-Bezeichnungen</b> nicht akzeptiert', $(Common.fieldsID['email'])); break;
						case 'fr': Common.error('Vous n&#39;avez pas accept&eacute; les <b>termes de vie priv&eacute;e</b>', $(Common.fieldsID['email'])); break;
						case 'es': Common.error('Usted no ha aceptado los <b>t&eacute;rminos de intimidad</b>', $(Common.fieldsID['email'])); break;
					};
				}
			}
		});
	}
},


Btns={
	send_reg:function(formName){
		if (MyForm.controls(formName) && MyForm.passwords() && MyForm.checkbox())
			MyAjax.request(formName);
	},
	send_cont:function(formName){
		/* if (MyForm.controls(formName) && MyForm.checkbox()) */
		if (MyForm.controls(formName) && MyForm.privacy_saeco())
			$(formName).submit();
	},
	send_compare:function(formName){
		//if (MyForm.compare(formName))
			$(formName).submit();
	},
	send_psw:function(formName){
		if (MyForm.controls(formName) && MyForm.passwords())
			$(formName).submit();
	},
	send:function(formName){
		if (MyForm.controls(formName)){
			console.log('ci va');
			$(formName).submit();
		}
	},
	send_search:function(formName){
		if (MyForm.controls(formName) && MyForm.checkDate())
			$(formName).submit();
	},
	resets:function(formName){
		$(formName).reset();
		if ($('province'))
			$('province').style.display = 'none';
		if ($(Common.fieldsID['nazione']))
			$(Common.fieldsID['nazione']).value='AF';
		all = $$('#'+formName+' ._*');
		for (i=0, l=all.length; i<l; i++){
			$(all[i]).removeClassName('inputError');
		}
	},
	rollover:function(div_id, div_class){
		$(div_id).className=div_class;
	},
	rollout:function(div_id, div_class){
		$(div_id).className=div_class;
	}
},


Event.observe(window, 'load', function(){
	Common.elements('form_registration||form_contact||login_form');

	// form contact
	if ($('form_contact')){
		if ($F(Common.fieldsID['nazione'])=='IT')
			$('province').style.display='block';
		
		/* privacy btn */
		Event.observe('privacy_show', 'click', function(event){event.stop(); MyForm.show('law');});
		
		// nations
		if ($(Common.fieldsID['nazione'])){
			aNation = $(Common.fieldsID['nazione']);
			Event.observe(aNation, 'change', function(){MyForm.nations();});
		}
		
		
		
		// browse_cont
		if ($('browse_cont')){
			Browse.invisible('browse_cont');
			Event.observe('browse_cont', 'change', function(){Browse.sendValue('browse_cont','file')});
		}
		
		

			Event.observe('send_cont', 'click', function(event){event.stop(); Btns.send_cont('form_contact');});

	}

	
	// form registration
	if ($('form_registration')){
		// no cache - duplicate email check
		MyAjax.noCache();
		
		// firefox radio default position
		MyForm.default_radio();
		
		// register as
		if ($('privato') || $('azienda')){
			Event.observe('privato', 'click', function(){MyForm.reg_as();});
			Event.observe('azienda', 'click', function(){MyForm.reg_as();});
		}
		
		// nations
		if ($(Common.fieldsID['nazione'])){
			aNation = $(Common.fieldsID['nazione']);
			Event.observe(aNation, 'change', function(){MyForm.nations();});
		}
		
		// browse_reg
		if ($('browse1')){
			Browse.invisible('browse1');
			Event.observe('browse1', 'change', function(){Browse.sendValue('browse1','file')});
		}
	
		// registration
		Event.observe('send_reg_'+Common.lang(), 'click', function(event){event.stop(); Btns.send_reg('form_registration');});
	}

	// login
	if ($('form_login'))
		Event.observe('send_login', 'click', function(event){event.stop(); Btns.send('form_login');});

	// login
	if ($('form_compare'))
		Event.observe('send_compare', 'click', function(event){event.stop(); Btns.send_compare('form_compare');});
		
	// password lost
	if ($('form_passwordlost'))
		Event.observe('send_psw', 'click', function(event){event.stop(); Btns.send_psw('form_passwordlost');});
		
	// new password 
	if ($('form_newpassword'))
		Event.observe('send_newpsw', 'click', function(event){event.stop(); Btns.send('form_newpassword');});
		
	// search engine
	if ($('form_search'))
		Event.observe('send_search_'+Common.lang(), 'click', function(event){event.stop(); Btns.send_search('form_search');});
});