﻿function IsNull(val){return(val==null || val.length==0);}
function IfNull(val,val2){if(val==null || val.length==0)return val2;else return val;}
function isInteger(s){return parseInt(s,10)===s;}
function fillZero(myString) {
if (myString.length == 1) return "0" + myString;
else return myString;
}
jQuery.fn.center=function(){this.css('top',( $(window).height() - this.height() ) / 2+$(window).scrollTop() -10 + 'px').css('left', ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + 'px');}
jQuery.fn.blink=function(){this.fadeIn(100).fadeOut(100).fadeIn(100).fadeOut(100).fadeIn(100).fadeOut(100).fadeIn(100).fadeOut(100).fadeIn(100).fadeOut(100).fadeIn(100);}
$.maxZIndex = $.fn.maxZIndex = function(opt) {
    var zmax = 0;
    $('.window').each(function(index){
        var cur = parseInt($(this).css('z-index'));
        zmax = cur > zmax ? cur : zmax;    	
    });
    zmax = parseInt(zmax)+1;
    
    if (!this.jquery)return zmax;
 	$(this).css('z-index',zmax);
 	return this;
}
$.fn.focus_first = function() {
  var elem = $('input:visible', this).get(0);
  var select = $('select:visible', this).get(0);
  if (select && elem) {
    if (select.offsetTop < elem.offsetTop) {
      elem = select;
    }
  }
  var textarea = $('textarea:visible', this).get(0);
  if (textarea && elem) {
    if (textarea.offsetTop < elem.offsetTop) {
      elem = textarea;
    }
  }
  
  if (elem) {
    elem.focus();
  }
  return this;
}
function checkForm(form,thisForm,act){
	$(form).ajaxSubmit(function(data){
		switch(act){
			case 'login':
				if(data!='OK'){alert(data);return;}
				if($(form.elements['login']).is(':checked')){
					$.cookie('login','on',{expires:365, path: '/'});
					$.cookie('username',form.elements['username'].value,{expires:365, path: '/'});
					$.cookie('password',form.elements['password'].value,{expires:365, path: '/'});					
				}
				else{
					$.cookie('login','',{expires:-1, path: '/'});
					$.cookie('username','',{expires:-1, path: '/'});
					$.cookie('password','',{expires:-1, path: '/'});
				}
				location.href='/'+form.elements['referer'].value;
			break;
		
			case 'register':
				if(data!='OK'){alert(data);return;}
				alert('Grazie per esserti registrato!<br/>Riceverai un\'email di conferma (se non la ricevi entro pochi minuti, controlla nella cartella dello spam!)',function(){location.href='/';});
			break;
			
			case 'registerCompleta':
				if(data!='OK'){alert(data);return;}
				alert('Grazie per aver completato la tua iscrizione!<br/>Riceverai un\'email di conferma (se non la ricevi entro pochi minuti, controlla nella cartella dello spam!)',function(){location.reload();});
			break;
		}//switch
	});
}
function showerror(error, target){
    var pos = target.position();
    var height = target.height();
    var newpos = { left: pos.left, top: pos.top + height + 2 }
    var form = target.closest('form');          
    error.appendTo(form).css(newpos);
}

function ControllaCF(cf)
{
	var validi, i, s, set1, set2, setpari, setdisp;
	if( cf == '' )  return false;
	cf = cf.toUpperCase();
	if( cf.length != 16 )
		return false;
	validi = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
	for( i = 0; i < 16; i++ ){
		if( validi.indexOf( cf.charAt(i) ) == -1 )
			return false;
	}
	set1 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	set2 = "ABCDEFGHIJABCDEFGHIJKLMNOPQRSTUVWXYZ";
	setpari = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	setdisp = "BAKPLCQDREVOSFTGUHMINJWZYX";
	s = 0;
	for( i = 1; i <= 13; i += 2 )
		s += setpari.indexOf( set2.charAt( set1.indexOf( cf.charAt(i) )));
	for( i = 0; i <= 14; i += 2 )
		s += setdisp.indexOf( set2.charAt( set1.indexOf( cf.charAt(i) )));
	if( s%26 != cf.charCodeAt(15)-'A'.charCodeAt(0) )
		return false;
	return true;
}

google.setOnLoadCallback(function(e){
	///////////////////////////////////////////////////////////////////////////////////////////////////////
	// Splash Email
	///////////////////////////////////////////////////////////////////////////////////////////////////////
	if($.cookie('email')!='on'&&$('#annunci').length){
		$('#emailForm').validate({
			errorElement: "div",
			errorClass: "cusErrorPanel",
			errorPlacement: function(error, element){
				showerror(error, element);
			},
		
			onfocusout: false,
			onkeyup: false,
			onclick: false,
			submitHandler: function(form){
				$.cookie('email','on',{expires:365});		
				$(form).ajaxSubmit(function(data){
					if(data=='OK'){$.unblockUI();}else alert(data);
				});	
			}	
		});
		$('#splashClose').click(function(){$.unblockUI();});
		$.blockUI({ message: $('#splash')});
	}
	/////////////////////////////////////////////////////////////////////////////////////////////////////
	// Generale
	/////////////////////////////////////////////////////////////////////////////////////////////////////
	$('form').validate({
		errorElement: "div",
		errorClass: "cusErrorPanel",
		errorPlacement: function(error, element){
			showerror(error, element);
		},
	
		onfocusout: false,
		onkeyup: false,
		onclick: false,
		focusCleanup: true,
		submitHandler: function(form){
			var act=form.elements['act'].value;
			if($('#cfiscale').length)if(!ControllaCF($('#cfiscale').val())){alert('Codice Fiscale non valido');return false;}
			// se la form ha classe conferma allora chiedo la conferma
			if($(form).is('.conferma')){
				confirm(IfNull($(form).attr('conferma'),'Confermi?'),function(){
					checkForm(form,this,act);
				});
			}
			else checkForm(form,this,act);
		}	
	});
	
	$('div.cusErrorPanel').live('mouseenter',function(){$(this).remove();});
	$('form').focus_first();
	//$('form, input, textarea').attr('autocomplete','off');
	/////////////////////////////////////////////////////////////////////////////////////////////////////
	// Ricerca
	/////////////////////////////////////////////////////////////////////////////////////////////////////
	$('#ricerca div').disableSelection();
	$('.button').disableSelection();
	
	$('#ricerca div').live('click',function(){
		ul=$(this).children('ul');
		if(!ul.length)return;
		if(ul.is(':visible')){
			ul.fadeOut('fast').children('li').remove();
			return;
		}
		$('#ricerca div ul').hide();

		ul.load('/_pages/ACT.asp?act=ricerca&tbl='+ul.parent('div').attr('title')+'&id='+$('#ricerca span').map(function(){return IfNull($(this).attr('value'),0);}).get().join(','),function(){
			ul.fadeIn('fast');
			
			$('#ricerca li.B').hoverIntent(function(){
				if($(this).is('.show')){
					$(this).removeClass('show').nextUntil('li.B').slideUp('slow');
					return;
				}
				//$('#ricerca li.B.show').removeClass('show').nextUntil('li.B').slideUp('slow');
				
				$(this).addClass('show').nextUntil('li.B').slideDown('slow');
			},function(){
				return;
//				$('#ricerca li.show').nextUntil('li.B').removeClass('show').hide('fast');
//				$(this).removeClass('show').nextUntil('li.B').slideUp('fast');
			});
			
		});
	});
	
	$('#ricerca li').live('click',function(){
		sp=$(this).closest('div').find('span');
		//if($(this).text().indexOf('[')<=0)return;
		ix=$('#ricerca span').index(sp);
		//se modificata la categoria, resetto regione e provicnia
		if(ix==0){
			$('#ricerca span').eq(1).html('Tutte le regioni').attr('value','0');
			$('#ricerca span').eq(2).html('Tutte le province').attr('value','0');
		}		
		//se modificata la regione, resetto la provicnia
		if(ix==1)$('#ricerca span').eq(2).html('Tutte le province').attr('value','0');

		sp.html($(this).text().split('[')[0]).attr('value',$(this).attr('value'));
		
		//$(this).closest('ul').fadeOut('fast').children('li').remove();
	});
	
	//$('#ricerca ul.sel').live('mouseleave',function(){$(this).fadeOut('fast');});
	
	$('#ricerca button').click(function(){
		id=$('#ricerca span').map(function(){return IfNull($(this).attr('value'),0);}).get().join(',');
		if(id=='0,0,0'&&!$('#textSearch').is('.changed')){location.href='/annunci/';return;}
		url='/annunci/?cerca='+id;
		if($('#textSearch').is('.changed'))url+='&search='+$('#textSearch').val();
		location.href=url;
	});
	
	$('#textSearch').focus(function(){
		if($(this).is('.changed'))return;
		$(this).val('');
	});
	$('#textSearch').focusout(function(){if($(this).val().length==0)$(this).val('cosa cerchi?').removeClass('changed');else $(this).addClass('changed')});
	$('#textSearch').keypress(function(e) {
		if(e.keyCode==13)location.href='/annunci/?search='+$(this).val();
	});
	////////////////////////////////////////////////////////////////////////
	// Messaggi
	////////////////////////////////////////////////////////////////////////
	$('#newMessage.red').click(function(){location.href='/annunci/?messaggi'});
	$('#newScambi').click(function(){location.href='/annunci/?scambi'});
	////////////////////////////////////////////////////////////////////////
	// Autologin
	////////////////////////////////////////////////////////////////////////
	if($.cookie('login')=='on'&&!$('#userLogged').length){
		$('#cookieLog').show().html('Bentornato <strong>'+$.cookie('username')+'</strong>.<div class="right mTop10">Vuoi <a href="#" class="viola">loggarti?</a></div>');
		$('#cookieLog a').click(function(e){
			$.post('/_pages/ACT.asp', {act:'login', username:$.cookie('username'), password: $.cookie('password')},function(data){
				if(data!='OK'){alert(data);return;}
				location.reload();
			});
			e.preventDefault();
		});
	}
	////////////////////////////////////////////////////////////////////////
	// Logout
	////////////////////////////////////////////////////////////////////////
	$('#logout').click(function(e){
		confirm('Vuoi uscire?',function(){
			$.post('/_pages/ACT.asp', {act:'logout'},function(){
				$.cookie('login','',{expires:-1, path: '/'});
				$.cookie('username','',{expires:-1, path: '/'});
				$.cookie('password','',{expires:-1, path: '/'});
				location.reload();
			});
		});
		e.preventDefault();
	});
	////////////////////////////////////////////////////////////////////////
	$('#annuncioFoto').fancybox({
		'transitionIn'		: 'none',
		'transitionOut'		: 'none',
		'titlePosition' 	: 'over',
		'titleFormat'		: 'none'
	});
	//////////////////////////////////////////////////
	// Iscrizione
	/////////////////////////////////////////////////
	$('#gasInfo').live('click',function(){
		$('#gasDIV').load('/_testi/iscrizione_gas.html',function(){
			$('#gasClose').click(function(){$('#gasDIV').slideUp();});
			$('#gasDIV').slideDown();
		});
	});
	
	$('#registerForm input:radio:first').live('click',function(){
		$('#gasDIV').load('/_pages/ACT.asp?act=gas',function(){
			$('#gasClose').click(function(){$('#gasDIV').slideUp();});
			$('#gasDIV').slideDown();
			
			$('#registerForm select[name="gasRegione"]').live('change',function(){
			 	$('#registerForm select[name="gasProvincia"]').load('/_pages/ACT.asp?act=gasProvincia&id='+$(this).val(),function(){$(this).removeAttr('disabled')});
			 	$('#registerForm select[name="gasComune"]').empty();
			 	$('#registerForm #gasNome').html('<select name="gasNome" disabled="disabled"></select>');
			});
			$('#registerForm select[name="gasProvincia"]').live('change',function(){
			 	$('#registerForm select[name="gasComune"]').load('/_pages/ACT.asp?act=gasComune&id='+$(this).val(),function(){$(this).removeAttr('disabled')});
			 	$('#registerForm #gasNome').html('<select name="gasNome" disabled="disabled"></select>');
			});			
			$('#registerForm select[name="gasComune"]').live('change',function(){
				$('#registerForm #gasNome').load('/_pages/ACT.asp?act=gasNome&id='+$(this).val(),function(){
					$(this).removeAttr('disabled');
					//$('#gasInserisciNome').click(function(){alert('ciao');});
					$('#registerForm select[name="gasNome"]').change(function(){
						if($(this).val()==0)$('#registerForm #gasNome').load('/_pages/ACT.asp?act=gasNomeInput',function(){$('#gasNome').find('input').focus();});
					});
				});
			});
			
//			$('#gasInserisciNome').live('click',function(){
//				$('#registerForm #gasNome').load('/_pages/ACT.asp?act=gasNomeInput',function(){$('#gasNome').find('input').focus();});
				//.html('<input type="text" name="gasNomeNew" class="required"/>',function(){alert('oo');$('#gasNome').find('input').focus();});
//			});
	
			$('#gasNuovo').live('click',function(e){
				$('#gasDIV').load('/_pages/ACT.asp?act=gasNuovo',function(){
					$('#registerForm select[name="gasRegione"]').live('change',function(){
					 	$('#registerForm select[name="gasProvincia"]').load('/_pages/ACT.asp?act=provincia&id='+$(this).val());
					 	$('#registerForm select[name="gasComune"]').empty();
					});
					$('#registerForm select[name="gasProvincia"]').live('change',function(){
					 	$('#registerForm select[name="gasComune"]').load('/_pages/ACT.asp?act=comune&id='+$(this).val());
					});
					$('#registerForm select[name="gasComune"]').live('change',function(){
					 	$('#registerForm input[name="gasNomeNew"]').removeAttr('disabled').focus();
					});			
	
				});
				e.preventDefault();
			});
		});
	});
	
	$('#registerForm input:radio:eq(1)').live('click',function(){
		$('#gasDIV').slideUp()
	});
	
	$('#registerForm select[name="regione"]').live('change',function(){
	 	$('#registerForm select[name="provincia"]').load('/_pages/ACT.asp?act=provincia&id='+$(this).val());
	 	$('#registerForm select[name="comune"]').empty();
	});
	$('#registerForm select[name="provincia"]').live('change',function(){
	 	$('#registerForm select[name="comune"]').load('/_pages/ACT.asp?act=comune&id='+$(this).val());
	});
	
	$('#registerForm td span').cluetip({arrows: true, sticky: false, cluetipClass: 'rounded', showTitle: false, ajaxCache: true, waitImage: false, dropShadow: true, closeText: '', mouseOutClose: true});
	
	$('#cfiscale').live('change',function(){
		if(!ControllaCF($(this).val()))alert('Codice Fiscale non valido');
	});
	///////////////////////////////////////////////////////////////////////////////////////////////////
	$('#social div.hidden').show();
});
