/* 
 * Javascript Utils Function
 */
var checkNickNameRet = false;
var checkEmailRet = false;
var errori="";
var isEmail=/^\w(\.?[\w-])*@\w(\.?[\w-])*\.[a-z]{2,6}(\.[a-z]{2})?$/i;
var isAlfaNum = /^[a-z0-9]/;
var isCap=/^\d{5}$/;
var isDateformat = /^\d{1,2}(\/)\d{1,2}\1\d{4}$/;
var nonNumeric = /\D/;

/*
 * Form submit
 */
function formsubmit(formId) {
	var form = document.getElementById(formId);
	form.submit();
}

/*
 * Form reset
 */
function formreset(formId) {
	var form = document.getElementById(formId);
	form.reset();
}

/* funzioni usate nel modulo di login / registrazione */
function viewReg(page,sp) {
		
	if (page=="2") {
		nome=document.getElementById("FrontUsersName").value;
		cognome=document.getElementById("FrontUsersLastname").value;
		nickname=document.getElementById("FrontUsersNickname").value;
		email=document.getElementById("FrontUsersEmail").value;
		password=document.getElementById("FrontUsersPassword").value;
		passwordConfirm=document.getElementById("FrontUsersPasswordConfirm").value;
		
		if (nome=="") {
			errori="&bull; Verifica la correttezza dei dati inseriti nel campo <b>Nome</b>.\n";
		}	
		if (cognome=="") {
			errori=errori+"&bull; Verifica la correttezza dei dati inseriti nel campo <b>Cognome</b>.\n";
		}
		if (nickname=="") {
			errori=errori+"&bull; Verifica la correttezza dei dati inseriti nel campo <b>Nickname</b>.\n";
		}
		if (nickname!="" && nickname.length < 4) {
			errori=errori+"&bull; Il campo <b>Nickname</b> deve essere almeno di 4 caratteri.\n";
		}
		if (email=="") {
			errori=errori+"&bull; Verifica la correttezza dei dati inseriti nel campo <b>E-mail</b>.\n";
		}
		if (email!="" && !isEmail.test(email)) {
			errori=errori+"&bull; Il campo <b>E-mail</b> non è in un formato corretto.\n";
		}
		if (password==""||password.length<8||!isAlfaNum.test(password)) {
			errori=errori+"&bull; Verifica la correttezza dei dati inseriti nel campo <b>Password</b>\n<i>(Ricorda che non e' consentito l'uso di caratteri speciali o lettere accentate, e che la password deve essere lunga almeno 8 caratteri)</i>.\n";
		}
		if (password!=passwordConfirm) {
			errori=errori+"&bull; Verifica che il campo <b>Conferma password</b> coincida con il campo <b>Password</b>.\n";
		}
		if (errori!="") {
			jAlert("<b>ATTENZIONE</b>:\n"+errori);
			errori="";
			return;			
		}
		checkNickname();
		if(checkNickNameRet) {
			jAlert('<b>ATTENZIONE</b>:\n&bull; Nickname gi&agrave; utilizzato.');
			return;
		}
		checkEmail();
		if(checkEmailRet) {
			jAlert('<b>ATTENZIONE</b>:\n&bull; Email gi&agrave; registrata.');
			return;
		}

	}
	
	if (page=="3") {
		email=document.getElementById("FrontUsersEmail").value;
		address=document.getElementById("FrontUsersAddress").value;
		zipcode=document.getElementById("FrontUsersZipcode").value;
		city=document.getElementById("FrontUsersCity").value;
		province=document.getElementById("FrontUsersProvince").value;		
		birthdate=document.getElementById("FrontUsersBirthdate").value;
		
		if (birthdate==""||!isDateformat.test(birthdate)) {
			errori=errori+"&bull; Verifica la correttezza dei dati inseriti nel campo <b>Data di nascita</b>.\n";
		}
		if (document.getElementById("parentdatas").style.display=='block') {
			//parentname=document.getElementById("FrontUsersParentname").value;
			//parentlastname=document.getElementById("FrontUsersParentlastname").value;
			//parentemail=document.getElementById("FrontUsersParentemail").value;
			if (document.getElementById("FrontUsersParentname").value=="") {
				errori=errori+"&bull; Verifica la correttezza dei dati inseriti nel campo <b>Nome del genitore</b>.\n";
			}
			if (document.getElementById("FrontUsersParentlastname").value=="") {
				errori=errori+"&bull; Verifica la correttezza dei dati inseriti nel campo <b>Cognome del genitore</b>.\n";
			}
			if (document.getElementById("FrontUsersParentemail").value=="" || !isEmail.test(document.getElementById("FrontUsersParentemail").value)) {
				errori=errori+"&bull; Verifica la correttezza dei dati inseriti nel campo <b>Email genitore</b>.\n";
			}
			if (document.getElementById("FrontUsersParentemail").value==email) {
				errori=errori+"&bull; I dati inseriti nel campo <b>Email genitore</b> non possono essere uguali ai dati del campo <b>Email</b>.\n";
			}
		}
		if (nonNumeric.test(document.getElementById("FrontUsersZipcode").value)) {
			errori=errori+"&bull; Il campo <b>CAP</b> deve contenere solo numeri.\n";
		}
		if (province=="") {
			errori=errori+"&bull; Verifica la correttezza dei dati inseriti nel campo <b>Provincia</b>.\n";
		}
		
		if (errori!="") {
			jAlert("<b>ATTENZIONE</b>:\n"+errori);
			errori="";
			return;			
		}
	}
	
	if (page=="4") {	
		//privacy=document.getElementById("privacy").checked;
		//okadvertising=document.getElementById("okadvertising").checked;
		
		var check="false";
		for (i=0; i<sp; i++) {
			dd="s"+i;
			//alert(dd);
			if (document.getElementById(dd).checked==true) {
				check="true";
			}
		}
		
		if (check=="false") {
			errori=errori+"&bull; Devi selezionare almeno uno sport preferito.\n";
		}
		if (document.getElementById("privacy").checked==false) {
			errori=errori+"&bull; Per completare la registrazione e' necessario acconsentire al trattamento della privacy.\n";
		}
		/*if (okadvertising=="") {
			errori=errori+"Per completare la registrazione e' necessario leggere e accettare i termini e le condizioni d'uso.\n";
		}*/
		if (errori!="") {
			alert("<b>ATTENZIONE</b>:\n"+errori);
			jAlert(text);
			errori="";
			return false;
		} else {
		formsubmit('FrontUsersRegisterForm');
		}
	}

	if(!page)
		page = 1;
	//funzione per visualizzare la registrazione
	hideReg();
	if(page!="4") {
		document.getElementById('registration' + page).style.display='block';
	} 
	
}
function hideReg() {
	//funzione per nascondere la registrazione
	document.getElementById('registration1').style.display='none';
	document.getElementById('registration2').style.display='none';
	document.getElementById('registration3').style.display='none';
}

function HideDIV(d) {
	document.getElementById(d).style.display = "none";
}

function DisplayDIV(d) {
	document.getElementById(d).style.display = "block";
}

function openPopup(url,pwidth,pheight,attributes) 
{
 var width  = pwidth;
 var height = pheight;
 var left   = (screen.width  - width)/2;
 var top    = (screen.height - height)/2;
 var params = "width="+width+", height="+height;
 params += ', top='+top+', left='+left;
 params += ", " + attributes + '"';
 newwin=window.open(url,'', params);
 if (window.focus) {newwin.focus()}
}

function genericPop(myUrl,myWinName,myWidth,myHeight,myPars) {
	var winl = (screen.width - myWidth) / 2;
	var wint = (screen.height - myHeight) / 2;
	parameters = myPars + '';
	if (parameters == '') parameters = ',toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=no';
	gwin=window.open(myUrl,myWinName,'width='+myWidth+',height='+myHeight+',left='+winl+',top='+wint+parameters);
	gwin.focus();
}

function checkBirthdateFormat() {
	birthdate=document.getElementById("FrontUsersBirthdate").value;
	if (birthdate==""||!isDateformat.test(birthdate)) {
		jAlert("ATTENZIONE: Verifica la correttezza dei dati inseriti nel campo Data di nascita.\n");
	} else {
		checkBirthdate();
	}	
}

/*
 * funzione per controllare unicit� nickname
 */

function checkNickname() {

	$.ajax({
      async: false,
      type: 'POST',
      url: appPath + 'front_users/checkNickname',
      dataType: 'html',
      data: "data[nickname] =" + $('#FrontUsersNickname').attr('value'),
      error: function(){
        jAlert("An error has occurred. Please try again.");
      },
      complete: function(data) {
    	  checkNickNameRet = (data.responseText == 'true');
      }
    });
    
}

/*
 * funzione per controllare unicit� email
 */

function checkEmail() {
	
	$.ajax({
      async: false,
      type: 'POST',
      url: appPath + 'front_users/checkEmail',
      dataType: 'html',
      data: "data[email] =" + $('#FrontUsersEmail').attr('value'),
      error: function(){
        jAlert("An error has occurred. Please try again.");
      },
      complete: function(data) {
    	  checkEmailRet = (data.responseText == 'true');
      }
    });
    
}

/*
 * funzione per controllare data di nascita
 */

function checkBirthdate() {
	
	$.ajax({
      async: false,
      type: 'POST',
      url: appPath + 'front_users/checkBirthdate',
      dataType: 'html',
      data: "data[birthdate] =" + $('#FrontUsersBirthdate').attr('value'),
      error: function(){
        jAlert("An error has occurred. Please try again.");
      },
      complete: function(data) {
    	  if (data.responseText == 'true') {
    		  $("#parentdatas").css("display", "block");
    	  } else {
    		  $("#parentdatas").css("display", "none");
    	  }
      }
    });
    
}

/*
 * funzione per inviare il voto al server
 */
 
function doVote(voto,elem,usr){
		$.ajax({
	      async: false,
	      type: 'POST',
	      url: appPath + 'front_users/doVote',
	      dataType: 'html',
	      data: "data[voto]=" + voto + "&data[elem]=" + elem + "&data[usr]=" + usr,
	      error: function(){
	        jAlert("An error has occurred. Please try again.");
	      },
	      complete: function(data) {
		      if (data.responseText == 'true') {
	    		   $("#stelle").html('<span style="color: rgb(85, 96, 111) ! important;">Grazie per aver votato!</span>');
	    	  } else {
	    		   $("#stelle").html('<span style="color: rgb(85, 96, 111) ! important;">Hai gi&agrave; votato questo contenuto!</span>');
	    	  }
	    	  getVote(elem);
	      }
	    });
}

function getVote(elem){
		$.ajax({
	      async: false,
	      type: 'POST',
	      url: appPath + 'front_users/getElementVote',
	      dataType: 'html',
	      data: "data[content_id]=" + elem,
	      error: function(){
	        //jAlert("An error has occurred. Please try again.");
	      },
	      complete: function(data) {
	      			//alert(data.responseText);
	      			var stringa = data.responseText;
	      			var splitted = stringa.split("-");
	      			var numvoti = splitted[0];
	      			var media = splitted[1];
	      			var numvoti_str = "";
	      			var stelle = "nessun voto";
	      			if (numvoti=='1') {
	      				numvoti_str=' voto';
	      			} else {
	      				numvoti_str=' voti';
	      			}
	      			var stella='<img alt="*" src="/img/icon06.gif"/>';
	    		    if (media=="1") stelle='Voto medio: '+stella+'&nbsp;<span style="color:#55606F">('+numvoti+numvoti_str+')</span>'
	    		    if (media=="2") stelle='Voto medio: '+stella+stella+'&nbsp;<span style="color:#55606F">('+numvoti+numvoti_str+')</span>'
	    		    if (media=="3") stelle='Voto medio: '+stella+stella+stella+'&nbsp;<span style="color:#55606F">('+numvoti+numvoti_str+')</span>'
	    		    if (media=="4") stelle='Voto medio: '+stella+stella+stella+stella+'&nbsp;<span style="color:#55606F">('+numvoti+numvoti_str+')</span>'
	    		    if (media=="5") stelle='Voto medio: '+stella+stella+stella+stella+stella+'&nbsp;<span style="color:#55606F">('+numvoti+numvoti_str+')</span>'
	    		    
	    		    //innerHtml
	    		    $("#star").html(stelle);
	      }
	    });
}

function addbookmark(title,pagina){
	if (window.sidebar) {
		// versione FF
		window.sidebar.addPanel(title, pagina,'');
	}
	else if( window.external ) {
		// versione IE
		window.external.AddFavorite( pagina, title);
	}
}
	
function sendMailTo() {
	location.href='mailto:?subject=Visita il sito Kinder+Sport&body='+window.location.href;
}


function jAlertE(val) {
	$(document).ready(function() {
		jAlert(val);
	});

}

//
function loadtext(desc,tag,elem){
	elem = (elem=='undefined'?'':elem);
	desc = (desc=='undefined'?'':desc);
	tag = (tag=='undefined'?'':tag);
	var base_url_tag = '/front_searchresults/tag/';
	var tag_sp = tag.split(',');
	var tag_str = '';
	for(var i=0; i<tag_sp.length; i++) {
		tag_str += '<a href="' + base_url_tag + jQuery.trim(tag_sp[i]) + '">'+tag_sp[i]+'</a>, ';
	}
	if(tag_str.length > 0)
		tag_str = tag_str.substring(0,tag_str.length-2);
		
	if(document.getElementById('desc')) document.getElementById('desc').innerHTML=desc;
	if(document.getElementById('tag')) document.getElementById('tag').innerHTML=tag_str;
	if(document.getElementById('elem')) document.getElementById('elem').value=elem;
	if('' != elem) getVote(elem);
}



//close overlayer
function close_layer() {
	if (document.getElementById('flashCappellinoswf')) {
	document.getElementById('flashCappellinoswf').disabled = true;
	document.getElementById('flashCappellinoswf').style.display = 'none';
	document.getElementById('flashCappellinoswf').style.visibility = "hidden";
	}
} //fine funzione


//open overlayer
function open_layer() {
	if (document.getElementById('flashCappellinoswf')) {
	document.getElementById('flashCappellinoswf').disabled = false;
	document.getElementById('flashCappellinoswf').style.display = 'block';
	document.getElementById('flashCappellinoswf').style.visibility = "visible";
	}
} //fine funzione

//jQuery lightbox
$(function() {
	$('a.lightbox').lightBox({
	imageLoading: '/img/lightbox-ico-loading.gif',
	imageBtnClose: '/img/lightbox-btn-close.gif',
	imageBtnPrev: '/img/lightbox-btn-prev.gif',
	imageBtnNext: '/img/lightbox-btn-next.gif',
	txtImage: 'Foto',
	txtOf: 'di'
	});
});

//jQuery lightBox Wrapper per richiamarla dal flash
function eLightBox(path, title) {
	var link = $('<a href="' + path + '" title="' + title + '"/>');
	link.lightBox({
		imageLoading: '/img/lightbox-ico-loading.gif',
		imageBtnClose: '/img/lightbox-btn-close.gif',
		imageBtnPrev: '/img/lightbox-btn-prev.gif',
		imageBtnNext: '/img/lightbox-btn-next.gif',
		txtImage: 'Foto',
		txtOf: 'di'
	});
	link.click();
}