// Document JavaScript
// Programat per bocaseca@motocross.es
// Si tens algun dubte o suggerencia, escriu-me!

var currenturl = location.href;
if(currenturl.indexOf('www') == -1){
	splitted_url = currenturl.split("http://");
	document.location.href = 'http://www.' + splitted_url[1];
}

//compatibilitza js amb swf suportant ie, ff
function thisMovie(movieName) {
	// IE and Netscape refer to the movie object differently.
	// This function returns the appropriate syntax depending on the browser.
	if (navigator.appName.indexOf ("Microsoft") !=-1) {
	   return window[movieName]
	}else{
		return document[movieName]
	}
}

//registre
var reg_sobreti = false;
var reg_web = false;
var reg_motopropia = false;




	//*******************//
	//** GENERICO **//
	
	function esNumerico(x) {
		var RegExp = /^(-)?(\d*)(\.?)(\d*)$/;
		var resultado = x.match(RegExp);
		return resultado;
	}


	//*******************//
	//** MENSAJES **//

	function set_error(id, text){
		document.getElementById(id).innerHTML = text;
		document.getElementById(id).style.display = 'block';
		document.getElementById(id).className = 'msg_error';
		new Effect.Highlight(id,{duration:1.0});
		//setTimeout("new Effect.Fade('" + id + "',{duration:1.0});",6000);
	}
	function set_info(id, text){
		document.getElementById(id).innerHTML = text;
		document.getElementById(id).style.display = 'block';
		document.getElementById(id).className = 'msg_info';
		new Effect.Highlight(id,{duration:1.0});
	}

	//*************//
	//** MAPS **//
	
	var map = null;
	var geocoder = null;

	function load() {
		if (GBrowserIsCompatible()) {
			map = new GMap2(document.getElementById("map"));
			map.addControl(new GSmallMapControl());
			map.addControl(new GMapTypeControl());
			map.setCenter(new GLatLng(42.000564,1.277869), 17);
			map.setMapType(G_SATELLITE_MAP);
			geocoder = new GClientGeocoder();
		}
	}
	
	
	//*************//
	//** Funcions generiques dels WIDGETS **//
	
	//Funzione che restituisce le dimensioni della finestra
	//Funzione presa da Lightbox V2
	function getWindowSize(){
		
		var xScroll, yScroll;
		
		if (window.innerHeight && window.scrollMaxY) {	
			xScroll = window.innerWidth + window.scrollMaxX;
			yScroll = window.innerHeight + window.scrollMaxY;
		} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
			xScroll = document.body.scrollWidth;
			yScroll = document.body.scrollHeight;
		} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
			xScroll = document.body.offsetWidth;
			yScroll = document.body.offsetHeight;
		}
		
		var windowWidth, windowHeight;
	
		if (self.innerHeight) {	// all except Explorer
			if(document.documentElement.clientWidth){
				windowWidth = document.documentElement.clientWidth; 
			} else {
				windowWidth = self.innerWidth;
			}
			windowHeight = self.innerHeight;
		} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
			windowWidth = document.documentElement.clientWidth;
			windowHeight = document.documentElement.clientHeight;

		} else if (document.body) { // other Explorers
			windowWidth = document.body.clientWidth;
			windowHeight = document.body.clientHeight;
		}
		
		////alert(xScroll + " x " + yScroll + " --- " + windowWidth + " x " + windowHeight);
		
		// for small pages with total height less then height of the viewport
		if(yScroll < windowHeight){
			pageHeight = windowHeight;
		} else { 
			pageHeight = yScroll;
		}
	
	
		// for small pages with total width less then width of the viewport
		if(xScroll < windowWidth){	
			pageWidth = xScroll;		
		} else {
			pageWidth = windowWidth;
		}
	
		arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
		return arrayPageSize;
	}//end function
	
	function doOverlay(id,width,height){

		var arrayDim = getWindowSize();	
		var background = id + "_back";
		document.getElementById(id).style.display = 'block';
		//IE6 error?
		//if(navigator.appName != 'Microsoft Internet Explorer'){
			document.getElementById(background).style.width = arrayDim[0] + "px";
			document.getElementById(background).style.height = arrayDim[1] + "px";
		/*	var ancho = arrayDim[0]/2;
		}else{
			var ancho = false;
		}*/
		
		var itemcontent = id + "_content";
		if(itemcontent == 'signin_content'){
			document.getElementById('signin_content').style.margin='-175px -250px';
		}
		newbox(itemcontent,width,height);
	}

	function newbox(itemcontent,width,height){
		document.getElementById(itemcontent).style.width = width +"px";
		document.getElementById(itemcontent).style.height = height +"px";
	}
	
	//titulo no sera la id?? sospito q si
	function carga_swf(swf,destino,titulo,width,height,version){
		var so = new SWFObject(swf, titulo, width, height, version, "white");
		so.addParam("wmode", "transparent");
		so.addParam("quality", "high");
		so.addParam("menu", "false");
//		so.addParam("swLiveConnect", "true");
//no te sentit?		so.addParam("id", "flash_pizarra");
		so.write(destino);
	}
	
	function closeOverly(id){
		var element = document.getElementById(id);
		element.style.display = 'none';	
	}
	
	
	//*************//
	//** LOGIN **//
	function activarUsuario(procedencia){
		if(procedencia == '' || procedencia == undefined){
			procedencia == 'login';
		}
		makeRequestPost('include/ajax_query/get_user_session.php');
		http_request.onreadystatechange = function(){
			if (http_request.readyState == 4) {
				if (http_request.status == 200) {
					resposta = http_request.responseText;
					valor = resposta.split("*");
					if(valor[0] == 'true'){
						new Effect.toggle('user_log', 'slide',{duration: 0.8})
						document.getElementById(procedencia + '_content').innerHTML = "";
						closeOverly(procedencia);
						setTimeout('mostrarPanelUsuario()',1000)
						//new Effect.slide('user_log',{duration:1});
					}
				} else {
					alert('Hubo un problema al conectar, porfavor, avisame: bocaseca@motocross.es');
				}
			}
		}//end ajax function
	}//end function
	
	function mostrarPanelUsuario(){
		document.getElementById('user_log').style.display = 'none';
		//document.getElementById('user_log').innerHTML = '<img src="imagenes/layout/misc/icon_user_helmet.gif" /><span>&nbsp;<strong>' + valor[2] + '</strong> | <a href="usuarios/' + valor[1] + '">Mi cuenta</a> | <a href="#">Ayuda</a></span>';
		document.getElementById('user_log').innerHTML = '<img src="imagenes/layout/misc/icon_user_helmet.gif" /><span>&nbsp;<strong>' + valor[2] + '</strong></span>';
		new Effect.toggle('user_log', 'slide',{duration: 0.8});
		setTimeout('window.location.reload()',2000);
	}
	
	//*************//
	//** SIGNIN **//
	
	function signinCheck_01(){
		if(document.getElementById('nombre').value == ""){
			set_error('signin_msg_box', 'Porfavor, escribe tu nombre.');
			return false;
		}
		if(document.getElementById('apellidos').value == ""){
			set_error('signin_msg_box', 'Porfavor, escribe tus apellidos.');
			return false;
		}
		if(document.getElementById('hombre').checked == false && document.getElementById('mujer').checked == false){
			set_error('signin_msg_box', 'Porfavor, especif&iacute;ca si eres chico o chica.');
			return false;
		}

		var dia = document.getElementById('dia').value;
		if(dia == ""){
			set_error('signin_msg_box', 'Porfavor, escribe el dia de tu fecha de nacimiento.');
			return false;
		}else{
			if(esNumerico(dia)){
				if(dia > 31 || dia < 1){
					set_error('signin_msg_box', 'Atenci&oacute;n: Parece que has equivocado el dia de tu cumplea&ntilde;os.');
					return false;
				}
			}else{
				set_error('signin_msg_box', 'Esa dia no me suena..');
				return false;
			}
		}
		
		var mes = document.getElementById('mes').value;
		if(mes == ""){
			set_error('signin_msg_box', 'Porfavor, escribe el mes de tu fecha de nacimiento.');
			return false;
		}else{
			if(esNumerico(mes)){
				if(mes > 12 || mes < 1){
					set_error('signin_msg_box', 'Atenci&oacute;n: Ese mes no existe en mi calendario.');
					return false;
				}
			}else{
				set_error('signin_msg_box', 'De ese mes no me acuerdo..');	
				return false;
			}
		}

		var anno = document.getElementById('ano').value;
		if(anno == ""){
			set_error('signin_msg_box', 'Porfavor, escribe el a&ntilde;o en que naciste.');
			return false;
		}else{
			if(esNumerico(anno)){
				if(anno < 40){
					set_error('signin_msg_box', 'No creo que debas ir en moto a tu edad..');
					return false;
				}
			}else{
				set_error('signin_msg_box', 'Espero que hayas nacido durante el siglo XX ..');	
				return false;
			}
		}
		// pagina seguent
		document.getElementById('signin_msg_box').style.display = 'none';
		document.getElementById('p_01').style.display = 'none';
		document.getElementById('p_02').style.display = 'block';
	}//end function
	
	function signinCheck_02(){
		if(document.getElementById('poblacion').value == ''){
			set_error('signin_msg_box', 'Porfavor, escribe el nombre de tu ciudad o pueblo.');
			return false;
		}
		
		var provincia = document.getElementById('provincia').value;
		if(provincia == '' || provincia == '#' || provincia == '0'){
			set_error('signin_msg_box', 'Porfavor, especif&iacute;ca tu provincia.');
			return false;
		}
		
		var cp = document.getElementById('cp').value;
		if(cp == ''){
			set_error('signin_msg_box', 'Porfavor, escribe tu c&oacute;digo postal para confirmar tu procedencia.');
			return false;
		}else{
			MyPostSend = "cp="+cp+"&id_provincia="+document.getElementById('id_provincia').value;
			makeRequestPost('include/ajax_query/check_cp.php');
			http_request.onreadystatechange = function() {
				if (http_request.status == 200){
					if(http_request.responseText != 'true'){
						set_error('signin_msg_box', 'Parece que este no es tu c&oacute;digo postal, o has equivocado tu provincia');
						return false;
					}else{
						//continua comprovan la resta de dades del form..
						if(document.getElementById('recinto').value == '0'){
							set_error('signin_msg_box', 'Porfavor, elige el recinto al que m&aacute;s acostumbres a ir.');
							return false;
						}
						//pagina seguent
						document.getElementById('signin_msg_box').style.display = 'none';
						document.getElementById('p_02').style.display = 'none';
						document.getElementById('p_03').style.display = 'block';
					}
				}
			}//end ajax
		}
	}//end function
	
	function signinCheck_03(){
		var email = document.getElementById('email').value;
		var regexp = new RegExp('^([a-z0-9\._-]+)(@[a-z0-9\.-_]+)(\.{1}[a-z]{2,6})$');
		if(!(regexp.test(email))){
			set_error('signin_msg_box', 'Atenci&oacute;n: Por seguridad, necesito tu email de contacto.');
			return false;
		}
		//pagina seguent
		document.getElementById('signin_msg_box').style.display = 'none';
		document.getElementById('p_03').style.display = 'none';
		document.getElementById('p_04').style.display = 'block';		
	}//end function
	
	function signinCheck_04(){
		var username = document.getElementById('nickname').value;
		if (username == ''){
			set_error('signin_msg_box', 'Atenci&oacute;n: Debes escribir un nombre de usuario.');
			return false;
		}
		var pas = document.getElementById('password').value;
		var pas2 = document.getElementById('password2').value;
		if (pas == ''){
			set_error('signin_msg_box', 'Atenci&oacute;n: Debes escribir una contrase&ntilde;a');
			return false;
		}
		if (pas2 == '' || pas2 != pas){
			set_error('signin_msg_box', 'Atenci&oacute;n: La contrase&ntilde;a y su confirmaci&oacute;n parecen no coincidir.');
			return false;
		}		
		// tots els camps omplerts correctament, procedeixo a contrastar el nom d'usuari (ajax), i si es valid, a registrar.
		MyPostSend = "nombre="+document.getElementById('nombre').value;
		MyPostSend += "&apellidos="+document.getElementById('apellidos').value;
		MyPostSend += "&nickname="+document.getElementById('nickname').value;
		MyPostSend += "&password="+document.getElementById('password').value;
		MyPostSend += "&password2="+document.getElementById('password2').value;
		MyPostSend += "&email="+document.getElementById('email').value;
		MyPostSend += "&mes="+document.getElementById('mes').value;
		MyPostSend += "&dia="+document.getElementById('dia').value;
		MyPostSend += "&ano="+document.getElementById('ano').value;
		if(document.getElementById('hombre').checked == true){
			MyPostSend += "&sex=0";
			var sesso = 'o';
		}else{
			MyPostSend += "&sex=1";
			var sesso = 'a';
		}
		// Dades adicionals
		MyPostSend += "&poblacion="+document.getElementById('poblacion').value;
		var web_value = document.getElementById('web').value;
		if(reg_web == true && web_value != ''){
			MyPostSend += "&web="+web_value;
		}
		var motopropia_value = document.getElementById('motopropia').value;
		if(reg_motopropia == true && motopropia_value != ''){
			MyPostSend += "&motopropia="+motopropia_value;
		}
		var sobreti_value = document.getElementById('sobreti').value;
		if(reg_sobreti == true && sobreti_value != ''){
			MyPostSend += "&sobreti="+motopropia_value;
		}
		MyPostSend += "&id_provincia="+document.getElementById('id_provincia').value;
		MyPostSend += "&circuitohabitual="+document.getElementById('recinto').value;
		
		makeRequestPost('include/ajax_query/add_user.php');
		http_request.onreadystatechange = function() {
			if (http_request.readyState == 4) {
				if (http_request.status == 200) {
					resposta = http_request.responseText;
					valor = resposta.split("*");
					if(valor[0] == 'true'){
						var id_recien_llegado = valor[1];
						document.getElementById('reg_enviar').onclick = ''; //deshabilito x seguretat
						set_info('signin_msg_box', 'Bienvenid' + sesso + '!<br />');
						thisMovie('registrate').SetVariable('id_usuario',id_recien_llegado);
						thisMovie('registrate').SetVariable('lg',username);
						thisMovie('registrate').SetVariable('ps',pas);
						thisMovie('registrate').Play();
						//no funciona //setTimeout("thisMovie('registrate').SetVariable('id_usuario',id_recien_llegado);",3000);
					}else{
						switch(http_request.responseText){
						case 'nickname':
							set_error('signin_msg_box', 'Atenci&oacute;n: Este nombre de usuario ya est&aacute; tomado.');
							return false;
						case 'email':
							set_error('signin_msg_box', 'Atenci&oacute;n: Solo puedes registrarte una vez.');
							return false;
						default:
							set_error('signin_msg_box', 'Hubo un problema al conectar con el servidor.  Ayuda: bocaseca@motocross.es <p class="datos_tecnicos">Datos tecnicos:' + http_request.responseText + '</p>');
							return false;
						}
					}//end if
				}else{
					set_error('signin_msg_box', '(no ready): Hubo un problema al conectar con el servidor.  Ayuda: bocaseca@motocross.es');
					return false;
				}//end if status
			}//end if state
		}//end subfunction
	}//end function signinCheck_04
	
	//*************//
	//** COMENTARIOS **//
	
	function controlComentario(){
		if(document.getElementById('comentario').value == ''){
			alert('Debes escrivir algo!');
			return false;
		}

		MyPostSend = "&comentario="+document.getElementById('comentario').value;
		MyPostSend += "&id="+document.getElementById('id').value;
		MyPostSend += "&catname="+document.getElementById('catname').value;
		makeRequestPost('include/ajax_query/add_talk.php');
		http_request.onreadystatechange = function(){
			if (http_request.readyState == 4) {
				if (http_request.status == 200) {
					if(http_request.responseText == 'true'){
						document.getElementById('enviar_comentario').onclick = 'void(0);';
						document.getElementById('enviar_comentario').innerHTML = 'Enviado';
						document.getElementById('enviar_comentario').href = 'javascript:void(0);';
						alert('ok!');						
						//new Effect.slide('user_log',{duration:1});
					}
				} else {
					alert('Hubo un problema al conectar, porfavor, avisame: bocaseca@motocross.es');
				}
			}
		}//end ajax function
	}
	
	//*************//
	//** EVENTOS & USUARIOS **//
	
	function getTracks4aut(id_aut,modulo){
		MyPostSend += "&id_aut="+id_aut;
		makeRequestPost('include/ajax_query/get_tracks4aut.php');
		http_request.onreadystatechange = function(){
			if (http_request.readyState == 4) {
				if (http_request.status == 200) {
					resposta = http_request.responseText;
					valor = resposta.split("*");
					if(valor[0] == 'true'){
						if(modulo == 'agregar_evento'){
							document.getElementById('recinto_wrapper').innerHTML = valor[1] + '<option value="0"></option><option value="agregar">- No est&aacute;, quiero agregar un recinto -</option></select><div id="ok_ajax" style="float:left; margin-left:5px;"></div>';
							carga_swf('imagenes/layout/misc/ok_flash_ajax.swf','ok_ajax','ok','16','16','9');
						}
						if(modulo == 'alta_usuario'){
							document.getElementById('recinto_wrapper').innerHTML = valor[1] + '<option value="0"></option><option value="">- No est&aacute; / No voy en moto -</option></select>';
							document.getElementById('recinto').className = 'texto_normal';
							document.getElementById('recinto').style.width = '146px';
						}
					}else{
						set_error('mensaje', 'Error: Hubo un problema al descargar los datos de los recintos.');
						return false;
					}
				} else {
					set_error('mensaje', 'Error: Hubo un problema al conectar con el servidor. Contactame a: bocaseca@motocross.es');
				}
			}
		}//end function
	}//end function
	
	//alta usuario, circuits x aut:
	function recargar(){
		var valor = document.getElementById('provincia').value;
		valor = valor.split("*");
		var idpro = valor[0];
		var idaut = valor[1];
		
		document.getElementById('id_provincia').value = idpro;
		document.getElementById('id_autonomia').value = idaut;
	
		getTracks4aut(idaut,'alta_usuario');
	}
	

	function votar(valor,id_elemento,modulo){
		if(modulo == undefined || modulo == '' || modulo == 'eshop'){
			var script = 'votar_eshop.php';
		}
		if(modulo == 'ewrite'){
			var script = 'votar_ewrite.php';	
		}
		//control seguretat
		if(script == undefined || script == ''){
			alert('Error desconocido: contactame a bocaseca@motocross.es');
			return false;
		}
		MyPostSend = "&valor="+valor;
		MyPostSend += "&id_elemento="+id_elemento;
		makeRequestPost('include/ajax_query/'+script);
		http_request.onreadystatechange = function(){
			if (http_request.readyState == 4) {
				if (http_request.status == 200) {
					switch(http_request.responseText){
					case 'true':
						alert('Tu voto ha sido añadido.');
						return false;
					case 'repetido':
						alert('Ya has votado aquí, no puedes repetir.');
						return false;
					default:
						set_error('mensaje', 'Hubo un problema al conectar con el servidor.<br />Es posible que tu sesi&oacute;n haya caducado, recarga pagina o vuelve a autentifacrte. <p class="datos_tecnicos">Datos tecnicos:' + http_request.responseText + '</p>');
						return false;
					}
				}else{
					set_error('mensaje', 'Error: No se pudo conectar con el servidor');
					return false;
				}
			}
		}//end subfunction
	}//end function