numero_fotos = 1;

function seguimientoGoogle(url){
	//alert(url);
	//pageTracker._trackPageview(url); 
	
}

function cargaEventos(fecha,ordre,ascdesc,cerca){
	var browser=navigator.appName;
	document.getElementById('cerca').value ="";
	if(fecha =="") {
		seguimientoGoogle('home');
		
		/*if(browser=="Microsoft Internet Explorer"){
			dhtmlHistory.add('home');
		}else{
			$.historyLoad('home');
		}*/
		
	}else{
		seguimientoGoogle('events/data-'+fecha);
		/*if(browser=="Microsoft Internet Explorer"){
			dhtmlHistory.add('events/data-'+fecha);
		}else{
			$.historyLoad('events/data-'+fecha);
		}*/
		
	}
	loading('contenido_dinamico');
	activaBotoAfegir();
	
	
	$.ajax({
			   type: "POST",
			   url: "secciones/events/events.php",
			   data: "ajax=1&data="+fecha+"&ordre="+ordre+"&ascdesc="+ascdesc+"&cerca=-1",
			   success: function(msg){
					document.getElementById('contenido_dinamico').innerHTML =msg;
					//if(browser!="Microsoft Internet Explorer"){
						inicializa_history();
					//}
			    }
			 });
}
function compruebaEvento(fecha){
	ret = 2;
	$.ajax({
			   type: "POST",
			   url: "secciones/events/hiha_events.php",
			   data: "ajax=1&data="+fecha,			   
			   success: function(msg){
					if(msg==1){
					cargaEventos(fecha,'','',-1);
					var browser=navigator.appName;
					if((browser!="Microsoft Internet Explorer")&&(browser!="Opera")){
						$.historyLoad('events/data-'+fecha);
					}else{
						dhtmlHistory.add('events/data-'+fecha);
					}
					}

			    }
			 });
			 return ret;
	
}
function cargaCerca(ordre,ascdesc,cerca_){
	
	cerca = document.getElementById('cerca').value;
	if(cerca=="") cerca = cerca_;
	if((cerca!="")&&(cerca!=-1)){

		loading('contenido_dinamico');
		activaBotoAfegir();
		
		$.ajax({
				   type: "POST",
				   url: "secciones/events/events.php",
				   data: "ajax=1&cerca="+cerca+"&ordre="+ordre+"&ascdesc="+ascdesc,			   
				   success: function(msg){
						document.getElementById('contenido_dinamico').innerHTML =msg;
						/*var browser=navigator.appName;
						if(browser!="Microsoft Internet Explorer"){*/
							inicializa_history();
						//}
				    }
				 });
	}

}
function enviaAmic(id){
	
	
	loading('contenido_dinamico');
	/*var browser=navigator.appName;
	if(browser=="Microsoft Internet Explorer"){
			dhtmlHistory.add('enviar/'+id);
	}*/
	$.ajax({
			   type: "POST",
			   url: "secciones/comunes/enviar.php",
			   data: "ajax=1&op1="+id,			   
			   success: function(msg){
					document.getElementById('contenido_dinamico').innerHTML =msg;
			    }
			 });
	
}
function cargaDetall(permalink){
	seguimientoGoogle('events/'+permalink);
	/*var browser=navigator.appName;
	if(browser=="Microsoft Internet Explorer"){
			dhtmlHistory.add('events/'+permalink);
	}*/

	loading('contenido_dinamico');
	activaBotoAfegir();

	$.ajax({
	   type: "POST",
	   url: "secciones/events/events_detall.php",
	   data: "ajax=1&op1="+permalink,			   
	   success: function(msg){
			document.getElementById('contenido_dinamico').innerHTML =msg;
			//var browser=navigator.appName;
			//if(browser!="Microsoft Internet Explorer"){
				inicializa_history();
			//}
	    }
	 });

}
function desactivaBotoAfegir(){

	$(".bot_afegir").addClass("desactivado");
	var browser=navigator.appName;
	if(browser!="Microsoft Internet Explorer"){
		$("#boto_afegir").attr("onclick", "return false;");
	}
	
}
function activaBotoAfegir(){

	$(".bot_afegir").removeClass("desactivado");
	var browser=navigator.appName;
	if(browser!="Microsoft Internet Explorer"){
		$("#boto_afegir").attr("onclick", "afegirEvent(); return false;");
	}
}
function afegirEvent(){
	/*var browser=navigator.appName;
	if(browser=="Microsoft Internet Explorer"){
			dhtmlHistory.add('afegir-event');
	}*/
	seguimientoGoogle('afegir-event');
	loading('contenido_dinamico');
	desactivaBotoAfegir();
	$.ajax({
	   type: "POST",
	   url: "secciones/events/afegir.php",
	   data: "ajax=1",			   
	   success: function(msg){
			document.getElementById('contenido_dinamico').innerHTML =msg;
			//var browser=navigator.appName;
			//if(browser!="Microsoft Internet Explorer"){
				inicializa_history();
			//}
	    }
	 });
}
function condicions(){
	seguimientoGoogle('condicions');
	loading('contenido_dinamico');
	//var browser=navigator.appName;
	//if(browser=="Microsoft Internet Explorer"){
			//dhtmlHistory.add('condicions');
	//}
	
	$.ajax({
	   type: "POST",
	   url: "secciones/comunes/informacion-legal.php",
	   data: "ajax=1",			   
	   success: function(msg){
			document.getElementById('contenido_dinamico').innerHTML =msg;
			//if(browser!="Microsoft Internet Explorer"){
				inicializa_history();
			//}
	    }
	 });
}
function afegirFoto(){
	if(numero_fotos<5){
		numero_fotos++;
		document.getElementById('fotos').innerHTML +='<br /><input type="file" name="foto_'+numero_fotos+'" id="foto_'+numero_fotos+'" />';
	}else{
		$('#boto_mes_fotos').hide();
	}
}

function loading(capa){
	document.getElementById(capa).innerHTML = '<img class="loadimg" src="imgs/loading.gif" alt="loading &hellip;" />';
}



function enviaForm(){
		document.getElementById("message").innerHTML = "Enviant dades ...";
		$('#message').fadeIn("slow");
		nombre 			= document.getElementById("nom_event").value;
		data_dia 		= document.getElementById("data_dia").options[document.getElementById("data_dia").selectedIndex].value;
		data_mes		= document.getElementById("data_mes").options[document.getElementById("data_mes").selectedIndex].value;
		data_any		= document.getElementById("data_any").options[document.getElementById("data_any").selectedIndex].value;
		repite			=  document.getElementById("repite").checked;
		descripcio		= document.getElementById("descripcio").value;
		lloc_event		= document.getElementById("lloc_event").value;
		pais_event		= document.getElementById("pais_event").options[document.getElementById("pais_event").selectedIndex].value;
		nom_autor		= document.getElementById("nom_autor").value;
		mail_autor		= document.getElementById("mail_autor").value;
		leido		= document.getElementById("leido").checked;
		foto1 = document.getElementById("foto_1").value;

		var nombre		=		nombre.htmlEntities();		
		var descripcio	=		descripcio.htmlEntities();		
		var lloc_event	=		lloc_event.htmlEntities();		
		var pais_event	=		pais_event.htmlEntities();
		var nom_autor	=		nom_autor.htmlEntities();
		var mail_autor	=		mail_autor.htmlEntities();		
		
		todo_ok = false;
		if((nombre!="")&&(descripcio!="")&&(lloc_event!="")&&(pais_event!="")&&(leido)){
			
			if(mail_autor!=""){
				mail_valido = isValidEmail(mail_autor);
				if(mail_valido) todo_ok = true;
			}else{
				todo_ok = true;
			}
		}
		if(todo_ok){
		
			error_upload = false;
			file_ok = true;
			if(foto1!=""){

				$.ajaxFileUpload({
					url:'secciones/events/doajaxfileupload.php?fileupload=foto_1',
					secureuri:false,
					fileElementId:'foto_1',
					dataType: 'json',
					success: function (data, status){
						if(typeof(data.error) != 'undefined'){
							if(data.error != ''){
								alert(data.error);
								error_upload = true;
								file_ok = false;
							}else{
								alert(data.msg);
								
								if(data.msg=="ok"){								
									for(i=2;i< numero_fotos+1 ;i++){
										foto = document.getElementById("foto_"+i).value;
		
										if((!error_upload)&&(foto!="")){
											$.ajaxFileUpload({
												url:'secciones/events/doajaxfileupload.php?fileupload=foto_'+i,
												secureuri:false,
												fileElementId:'foto_'+i,
												dataType: 'json',
												success: function (data, status){
													if(typeof(data.error) != 'undefined'){
														if(data.error != ''){
															//alert(data.error);
															error_upload = true;
															file_ok = false;
														}else{
															alert(data.msg);
														}
													}
													
												},
												error: function (data, status, e){
													alert(e);
													error_upload = true;
												}
											}
											);
										}
									}
								}else{
									error_upload = true;
								}
										
							}
						}
					}
					,
					error: function (data, status, e){
						alert(e);
					}
					}
					);
					alert("error_upload="+error_upload);
				;
			}else{
				file_ok = true;
			}
			if((file_ok)&&(!error_upload)){
			
				$.ajax({
				   type: "POST",
				   url: "includes/inserta_event.php",
				   data: "ajax=1&OP_1=submit"+
				   "&nombre="+nombre+
				  "&data_dia="+data_dia+
				   "&data_mes="+data_mes+
				  "&data_any="+data_any+
				  "&repite="+repite+
				   "&descripcio="+descripcio+
				 
				   "&lloc_event="+lloc_event+
				
				   "&pais_event="+pais_event+
				   "&nom_autor="+nom_autor+
				   "&mail_autor="+mail_autor,
				 
				   
				   success: function(msg){
						//alert(msg); 
						tmp = msg.split("__");
	
						switch(tmp[0]){
							case "error1":
								$('#message').hide();
								document.getElementById("message").innerHTML = tmp[1];
								$('#message').fadeIn("slow");
							break;
							default:
								$('#message').hide();
								document.getElementById("message").innerHTML = tmp[0];
								numero_fotos =1;
								document.getElementById("fotos").innerHTML = '<label for="fotos_event">Fotos del event</label> <br /><input type="file" name="foto_1" id="foto_1" /> <a class="mes" href="#" title="afegir més fotos" onclick="afegirFoto(); return false;" id="boto_mes_fotos"><span>+</span>afegir m&eacute;s fotos</a>';
								document.getElementById("form_afegir").reset();
								$('#message').fadeIn("slow");
								
							break;
						} 
						
				   	//cargaDadesCapa(msg,'container_general');
				   }
				 });
			}else{
				$('#message').hide();
				document.getElementById("message").innerHTML = "Revisa els fitxers (tipus, jpg o gif, i pes, max. 300KB)"
				$('#message').fadeIn("slow");
			}
		}else{
			
			if((mail_autor!="")&&(!mail_valido)){
				$('#message').hide();
				document.getElementById("message").innerHTML = "Revisa el format del correu electrònic";
				$('#message').fadeIn("slow");
			}else{
				$('#message').hide();
				document.getElementById("message").innerHTML = "Els camps <span class=\"obligatori\">marcats en negreta</span> són obligatoris";
				$('#message').fadeIn("slow");
				if(nombre==""){
					$('#nom_event').addClass('olvidado');
				}else{
					$('#nom_event').removeClass('olvidado');
				}
				if(descripcio==""){
					$('#descripcio').addClass('olvidado');
				}else{
					$('#descripcio').removeClass('olvidado');
				}
				if(lloc_event==""){
					$('#lloc_event').addClass('olvidado');
				}else{
					$('#lloc_event').removeClass('olvidado');
				}
				if(!leido){
					$('#label_id').addClass('olvidado');
				}else{
					$('#label_id').removeClass('olvidado');
				}
				
			}
				
		}
	}
		
function enviaComentario(){
		document.getElementById("message_comentari").innerHTML = "Enviant dades ...";
		$('#message_comentari').fadeIn("slow");
		nom 			= document.getElementById("nom").value;
		comentari		= document.getElementById("comentari").value;
		id_evento		= document.getElementById("id_evento").value;

		var nom			=		nom.htmlEntities();		
		var comentari	=		comentari.htmlEntities();		
			
		
		if((nom!="")&&(comentari!="")){
			$.ajax({
				   type: "POST",
				   url: "inserta_comentari.php",
				   data: "ajax=1&OP_1=submit"+
				   "&nom="+nom+
				  "&comentari="+comentari+
				   "&id_evento="+id_evento,
				 
				   
				   success: function(msg){
						//alert(msg); 
						tmp = msg.split("__");
	
						switch(tmp[0]){
							case "error1":
								
								document.getElementById("message_comentari").innerHTML = tmp[1];
								$('#message_comentari').fadeIn("slow");
							break;
							default:
								
								document.getElementById("message_comentari").innerHTML = tmp[0];
								document.getElementById("form_comentari").reset();
								$('#message_comentari').fadeIn("slow");
								
							break;
						} 
						$('#message').fadeIn("slow");
				   	//cargaDadesCapa(msg,'container_general');
				   }
				 });
			
		}else{
			
			document.getElementById("message_comentari").innerHTML = "Els camps <span class=\"obligatori\">marcats en negreta</span> són obligatoris";
			$('#message_comentari').fadeIn("slow");
		}

	}

		
function enviaAUnAmic(){
		document.getElementById("message_enviar").innerHTML = "Enviant dades ...";
		$('#message_enviar').fadeIn("slow");
		elteu_nom 			= document.getElementById("elteu_nom").value;
		elteu_correu 			= document.getElementById("elteu_correu").value;
		nom_amic 			= document.getElementById("nom_amic").value;
		correu_amic 			= document.getElementById("correu_amic").value;
		comentari		= document.getElementById("comentari").value;
		id_evento		= document.getElementById("id_evento").value;

		var elteu_nom			=		elteu_nom.htmlEntities();		
		var nom_amic	=		nom_amic.htmlEntities();		
		var comentari	=		comentari.htmlEntities();	

		
		if((elteu_correu!="")&&(correu_amic!="")){
			
			mail_valido_1 = isValidEmail(elteu_correu);
			mail_valido_2 = isValidEmail(correu_amic);
			if((mail_valido_1)&&(mail_valido_2)){
				$.ajax({
					   type: "POST",
					   url: "includes/recomienda.php",
					   data: "ajax=1&OP_1=submit"+
					   "&elteu_nom="+elteu_nom+
					   "&elteu_correu="+elteu_correu+
					   "&nom_amic="+nom_amic+
					   "&correu_amic="+correu_amic+
					  "&comentari="+comentari+
					   "&id_evento="+id_evento,
					 
					   
					   success: function(msg){
							//alert(msg); 
							tmp = msg.split("__");
		
							switch(tmp[0]){
								case "error1":
									
									document.getElementById("message_enviar").innerHTML = tmp[1];
									$('#message_enviar').fadeIn("slow");
								break;
								default:
									
									document.getElementById("message_enviar").innerHTML = tmp[0];
									document.getElementById("form_enviar").reset();
									$('#message_enviar').fadeIn("slow");
									
								break;
							} 
							$('#message_enviar').fadeIn("slow");
					   	//cargaDadesCapa(msg,'container_general');
					   }
					 });
			}else{
				document.getElementById("message_enviar").innerHTML = "Introdueix formats de correu vàlids";
				$('#message_enviar').fadeIn("slow");
			}
			
		}else{
			document.getElementById("message_enviar").innerHTML = "Els camps <span class=\"obligatori\">marcats en negreta</span> són obligatoris";
			$('#message_enviar').fadeIn("slow");
		}

	}

function isValidEmail(str) {
   return (str.indexOf(".") >= 1) && (str.indexOf("@") > 0);
}

//	prototipo htmlentity en javascript
String.prototype.htmlEntities = function () {
   return this.replace(/&/g,'_AMP_').replace('>','_GRAN_').replace('<','_PETIT_').replace(/[+]/g,'_PLUS_').replace(/#/g,'_ALMO_');
};

//
//	History	//////////////////////////////////////////////////////////////////////////////////////////////////////
//

function historyChange(newLocation)
{
//alert(newLocation);
hash = newLocation;
if(hash) {
			// restore ajax loaded state

			seccion	= 	hash.split("/");
			hash	=	seccion[0];

 			temp_title = hash;

			switch(hash){
				case -1:
				case "home":
				case "":
				case "#":
					cargaEventos('','','',-1);
				break;
				case "enviar":
					if(seccion.length>1){
						enviaAmic(seccion[1])
					}
				break;
				case "events":
					if(seccion.length>1){

						//	Carga el detalle de un evento o listado de una fecha
						tmp = seccion[1].split("-");
						if(tmp[0]=="data"){
							cargaEventos(tmp[1]+'-'+tmp[2]+'-'+tmp[3],'','',-1);
						}else{
							cargaDetall(seccion[1]);	
						}
						
						temp_title+= " » "+seccion[1];
					}else{
						cargaEventos('','','',-1);
					}
				break;
				case "afegir-event":
					afegirEvent();
				break;
				



			}
		//	Asignamos un TITLE HTML de la página nuevo
		asigna_title(temp_title);


		} else {
			// start page
			$("#load").empty();
		}
	}


// Cambiamos el title de la página.
function asigna_title(hash){
		//title_tmp = title.toUpperCase();
		temp_title = "";
		path_title = hash.split("/");
		if(path_title.length>1){
			for(i=0;i<(path_title.length-1);i++){
				//alert(path_title[i]);
				temp_title += path_title[i]+" » ";
			}
		}else{
			temp_title = path_title[0] +" » ";
		}

		//document.title = DecodeHtmlEntities(temp_title)+"Calendari Intercultural  ";	
}
function inicializa_history(){
	// set onlick event for buttons
	$("a[@rel='history']").click(function(){
		// 
		var hash = this.href;
		//	quitamos la url básica, no interesa
		//hash = hash.replace('http://192.168.1.2/400.CAL.J23/', '');
		//hash = hash.replace('http://www.docemusic.com/', '');
		hash = hash.replace('http://www.aprenentdelanostrahistoria.org/calendari/', '');
		//Le quitamos la almoadilla #, por si tiene alguna al final
		hash = hash.replace(/^.*#/, '');
		// moves to a new page. 
		// pageload is called at once. 
		//	incorporamos en el history lo que hay en hash
		$.historyLoad(hash);

		asigna_title(hash);


		return false;
	});

}
function DecodeHtmlEntities(str){
		str =  str.replace(/_AMP_/g, '&').replace(/_GRAN_/g, '>').replace(/_PETIT_/g, '<').replace(/_PLUS_/g,'+').replace(/_ALMO_/g,'#').replace(/%20/g,' ');
		try{
			var txt = document.createElement('textarea');
			txt.innerHTML = str;
			return txt.value;
		}catch(e){
			return str;
		}
}
$(document).ready(function() {
var browser=navigator.appName;

if((browser=="Microsoft Internet Explorer")||(browser=="Opera")){
	//Simply initializes the dhtmlHistory object. No change needed.
	//dhtmlHistory.create();
	dhtmlHistory.initialize();
	
	//Adds a listener for browser's back/forward navigation. Just change "historyChange" to
	// your method of choice. Note that "historyChange" comes from step 4 above.
	dhtmlHistory.addListener(historyChange);
	dhtmlHistory.add('home');
}else{
		// Initialize history plugin.
	// The callback is called at once by present location.hash. 
	$.historyInit(historyChange);

	$.historyLoad('home');
}
	inicializa_history();
	});

