var PRODUCTOS = {};

PRODUCTOS.formatoFecha = 'dd/mm/yyyy';	// Formato de fecha que vamos a utilizar
PRODUCTOS.formatoHora = 'HH:mm';	// Formato de fecha que vamos a utilizar
PRODUCTOS.indiceNoticiaActual = '';
PRODUCTOS.edicion = '';

var dirPath = jQuery.url.attr('directory');
arrDatos = dirPath.split("/");
if(arrDatos[1] != '') {
	dirPath = "/" + arrDatos[1] + "/";
} 
switch(dirPath) {
	case '/vizcaya/':
		PRODUCTOS.edicion = '/vizcaya';
		break;
	case '/alava/':
		PRODUCTOS.edicion = '/alava';
		break;
	case '/murcia/':
		PRODUCTOS.edicion = '/murcia';
		break;
	case '/albacete/':
		PRODUCTOS.edicion = '/albacete';
		break;
	case '/alicante/':
		PRODUCTOS.edicion = '/alicante';
		break;
	default:
		PRODUCTOS.edicion = '';
		break;
}

PRODUCTOS.menu = function() {
	

	$("ul[class=menunav] li[class=activo]").each(function() {
		$(this).removeClass('activo');
	}
	);

	var urlPath = jQuery.url.attr('path');
	urlPath = urlPath.replace(PRODUCTOS.edicion, '');

	arrDatos = urlPath.split("/");
	if(arrDatos[1] != '') {
		urlPath = "/" + arrDatos[1] + "/";
	} else {
		urlPath = "/";
	}

	switch(urlPath) {
		case '/':
			$("li[id=mnportada]").addClass('activo');
			break;
		case '/actualidad/':
			$("li[id=mnnoticias]").addClass('activo');
			break;
		case '/clasificaciones/':
			$("li[id=mnclasificaciones]").addClass('activo');
			break;
		case '/fotos-videos/':
			$("li[id=mnfotos]").addClass('activo');
			break;
		case '/videos/':
			$("li[id=mnvideos]").addClass('activo');
			break;
		case '/tablon-anuncios/':
			$("li[id=mncomunidad]").addClass('activo');
			break;
		case '/comunidad/':
			$("li[id=mncomunidad]").addClass('activo');
			break;
		case '/federaciones/':
			$("li[id=mnfederaciones]").addClass('activo');
			break;
		default:
			$("li[id=mnportada]").addClass('activo');
			break;
	}

};

PRODUCTOS.timeHace = function(segundos) {
	var salida = "";
	segundos = parseInt(segundos);
	if(!isNaN(segundos)) {
		if(segundos < 3600) salida = "hace " + Math.floor(segundos/60) + " minutos";
		else if(segundos < 3600*2) salida = "hace una hora y " + Math.floor((segundos-3600)/60) + " minutos";
		else if(segundos < 3600*24) salida = "hace " + Math.floor(segundos/3600) + " horas";
		else if(segundos < 3600*48) salida = "hace un día y " + Math.floor((segundos-(3600*24))/3600) + " horas";
		else salida = "hace " + Math.floor(segundos/(3600*24)) + " días";
	}
	return salida;
}


PRODUCTOS.emailValido = function(valor) {
	var EmailOk = true;
	var AtSym = valor.indexOf('@');
	var Period = valor.lastIndexOf('.');
	var Space = valor.indexOf(' ');
	var Length = valor.length - 1;
	if ((AtSym < 1) || (Period <= AtSym+1) || (Period == Length ) || (Space  != -1)) {  
		  EmailOk = false;
	}
	return EmailOk;
};

PRODUCTOS.fechaValida = function(valor) {
	var formatoFechaReg = PRODUCTOS.formatoFecha;
	formatoFechaReg = formatoFechaReg.replace('dd','([0-2][0-9]|3[0-1])');
	formatoFechaReg = formatoFechaReg.replace('mm','(0[0-9]|1[0-2])');
	formatoFechaReg = formatoFechaReg.replace(/y/g,'[0-9]');
	formatoFechaReg = "^" + formatoFechaReg + "$";
	var ExpReg = new RegExp(formatoFechaReg);
	var fechaOK = ExpReg.test(valor);
	return fechaOK;
};

PRODUCTOS.horaValida = function(valor) {
	var formatoHoraReg =  PRODUCTOS.formatoHora;
	formatoHoraReg = formatoHoraReg.replace('HH','([0-1][0-9]|2[0-3])');
	formatoHoraReg = formatoHoraReg.replace('mm','([0-5][0-9])');
	formatoHoraReg = "^" + formatoHoraReg + "$";
	var ExpReg = new RegExp(formatoHoraReg);
	var horaOK = ExpReg.test(valor);
	return horaOK;
};

PRODUCTOS.fileValido = function(valor,extension) {
	var formatoFile = "^(.*)(\\\\|/)[\\w:\\s/_-]+\\.(" + extension + ")$";
	var ExpRegFile = new RegExp(formatoFile,"i");
	var fileOK = ExpRegFile.test(valor);
	return fileOK;
};

PRODUCTOS.precioValido = function(valor) {
	var formatoPrecio = "^[0-9]+(,[0-9]{1,2})?$";
	var ExpRegPrecio = new RegExp(formatoPrecio,"i");
	var precioOK = ExpRegPrecio.test(valor);
	return precioOK;
};

PRODUCTOS.checkForm = function(frm) {
	for(i=0;i<frm.length;i++) {
		campoForm = frm.elements[i];
		if(campoForm.disabled == false) {
			var datosCheck = campoForm.id.split('#');
			texto_explicativo = "";
			if(datosCheck[2])
				texto_explicativo = datosCheck[2];
			if(datosCheck[0].indexOf('*') != -1) {
				if(campoForm.value == "") {
					alert('No has rellenado el campo ' + datosCheck[1]);
					campoForm.focus();
					return false;
				}
			}
			if(datosCheck[0].indexOf('numero') != -1) {
				if(isNaN(campoForm.value)) {
					alert('El campo ' + datosCheck[1] + ' tiene que ser numérico.' + texto_explicativo);
					campoForm.focus();
					return false;
				}
			}
			if((datosCheck[0].indexOf('email') != -1) && (campoForm.value != "")) {
				if(!PRODUCTOS.emailValido(campoForm.value)) {
					alert('El campo ' + datosCheck[1] + ' tiene que ser un email');
					campoForm.focus();
					return false;
				}
			}
			if((datosCheck[0].indexOf('fecha') != -1) && (campoForm.value != "")) {
				if(!PRODUCTOS.fechaValida(campoForm.value)) {
					alert('El formato del campo ' + datosCheck[1] + ' no es válido');
					campoForm.focus();
					return false;
				}
			}
			if((datosCheck[0].indexOf('hora') != -1) && (campoForm.value != "")) {
				if(!PRODUCTOS.horaValida(campoForm.value)) {
					alert('El formato del campo ' + datosCheck[1] + ' no es válido');
					campoForm.focus();
					return false;
				}
			}
			if(datosCheck[0].indexOf('checkbox') != -1) {
				if(campoForm.checked == false) {
					alert('No has rellenado el campo ' + datosCheck[1]);
					return false;
				}
			}
			if(datosCheck[0].indexOf('radio') != -1) {
				var radioCheck = 0;
				eval('var radioElemento = frm.' + campoForm.name);
				for(j=0;j<radioElemento.length;j++) {
					if(radioElemento[j].checked) {
						radioCheck = 1;
						break;
					}
				}
				if(radioCheck == 0) {
					alert('No has rellenado el campo ' + datosCheck[1]);
					return false;
				}
			}
			if(datosCheck[0].indexOf('select') != -1) {
				if(campoForm.selectedIndex == 0) {
					alert('No has rellenado el campo ' + datosCheck[1]);
					return false;
				}
			}
			if(datosCheck[0].indexOf('selectMultiple') != -1) {
				seleccion = 0
				for(j=1;j<campoForm.length;j++) {
					if(campoForm.options[j].selected == true)
						seleccion = 1
				}
				if(seleccion == 0) {
					alert('No has rellenado el campo ' + datosCheck[1]);
					return false;
				}
			}
			var expReg = /[^A-Za-z0-9ñÑáéíóúÁÉÍÓÚüÜ_\s\¿\?\¡\!\<\>\.\,\:\;\(\)\@\#\$\€\%\&\\\/\*\=\+\-\{\}\[\]\ç\º\ª]/i;
			if(datosCheck[0].indexOf('parsear') != -1) {
				if(expReg.test(campoForm.value)) {
					alert('El campo ' + datosCheck[1] + ' no es válido\n');
					campoForm.focus();
					return false;
				}
			}
			if((datosCheck[0].indexOf('min') != -1) && (campoForm.value != "")) {
				posicion = datosCheck[0].indexOf('min') + 3;
				limite = "0";
				while((!isNaN(datosCheck[0].substring(posicion,posicion + 1))) && (posicion < datosCheck[0].length)) {
					limite = limite + datosCheck[0].substring(posicion,posicion + 1);
					posicion = posicion + 1;
				}
				limite = parseInt(limite,10);
				if(campoForm.value.length < limite) {
					alert('El campo ' + datosCheck[1] + ' tiene que tener al menos ' + limite + ' caracteres\n');
					campoForm.focus();
					return false;
				}
			}
			if((datosCheck[0].indexOf('max') != -1) && (campoForm.value != "")) {
				posicion = datosCheck[0].indexOf('max') + 3;
				limite = "0";
				while((!isNaN(datosCheck[0].substring(posicion,posicion + 1))) && (posicion < datosCheck[0].length)) {
					limite = limite + datosCheck[0].substring(posicion,posicion + 1);
					posicion = posicion + 1;
				}
				limite = parseInt(limite,10);
				if(campoForm.value.length > limite) {
					alert('El campo ' + datosCheck[1] + ' tiene que como máximo ' + limite + ' caracteres\n');
					campoForm.focus();
					return false;
				}
			}
			if(datosCheck[0].indexOf('foto') != -1) {
				if((campoForm.value != "") && !PRODUCTOS.fileValido(campoForm.value,'jpeg|jpg|gif')) {
					alert('El formato de la foto no es correcta. Verifique que es un JPEG o un GIF o que el nombre no tiene acentos, espacios o caracteres extraños.');
					campoForm.focus();
					return false;
				}
			}
			if(datosCheck[0].indexOf('mp3') != -1) {
				if((campoForm.value != "") && !PRODUCTOS.fileValido(campoForm.value,'mp3')) {
					alert('El formato del mp3 no es correcto. Verifique que es un MP3 o que el nombre no tiene acentos, espacios o caracteres extraños.');
					campoForm.focus();
					return false;
				}
			}
			if(datosCheck[0].indexOf('acepto') != -1) {
				if(campoForm.checked == false) {
					alert('Tienes que aceptar las condiciones');
					return false;
				}
			}
			if(datosCheck[0].indexOf('precio') != -1) {
				if((campoForm.value != "") && !precioValido(campoForm.value)) {
					alert('El formato del precio no es correcto. El formato correcto es 1000,11.');
					campoForm.focus();
					return false;
				}
			}
			if(datosCheck[0].indexOf('repetir') != -1) {
				if(campoForm.value != frm.elements[i-1].value) {
					alert('El campo ' + datosCheck[1] + ' no coincide.');
					campoForm.focus();
					return false;
				}
			}
		}
	}
	return true;
};

PRODUCTOS.envFormFichero = function (frm, funcion) {
	if(funcion == null || funcion == '') {
		funcion = PRODUCTOS.respEnvFormFichero;
	}
	if(PRODUCTOS.checkForm(frm)) {
		//iframeObj = $('<iframe name="ifr_fichero" id="ifr_fichero" src="about:blank" width="600" height="600" frameborder="1" scrolling="no"/>');
		iframeObj = $('<iframe name="ifr_fichero" id="ifr_fichero" src="about:blank" width="0" height="0" frameborder="1" scrolling="no"/>');
		$(iframeObj).load(function() {funcion($(this).get(0).contentWindow.document.body.innerHTML)});
		if($("#ifr_fichero"))
			$("#ifr_fichero").remove();
		$(frm).after(iframeObj);
		frm.target = $(iframeObj).attr("name");
		frm.submit();
	}
};

PRODUCTOS.respEnvFormFichero = function(respuesta) {
	return respuesta;
};

PRODUCTOS.estaLogeado = function() {
	//return true;
	return $.cookie('queid_log') != '' && $.cookie('queid_log') != null;
};

PRODUCTOS.rotaNoticias = function(indice, clase, id_capa) {
	if($(".div_galeria_contento").length > 0) {	
		if(id_capa == null) {
			criterio = "." + clase;
		} else {
			criterio = "#" + id_capa;
		}
		PRODUCTOS.indiceNoticiaActual = '';
		if(indice == null) {			
			//$(criterio + " .gcnav").hide();
			$(criterio + " .div_galeria_contento").each( function(index) {
				if(index > 0) {
					$(this).hide();
				}
			});
			
			$(criterio + " .not_foto").each( function() {
				$(this).attr({ href: "javascript:void(0)"});
				/*
				$(this).mouseover( function() {
					$(this).parent().parent().parent().find(".gcnav").show();
				});
				$(this).mouseout( function() {	
					$(this).parent().parent().parent().find(".gcnav").hide();
				});
				*/
			}); 

			$(criterio + " .gcnav").each( function() {
				$(this).attr({ href: "javascript:void(0)"});
				/*
				$(this).mouseover( function() {
					$(this).parent().parent().parent().find(".gcnav").show();
				});
				$(this).mouseout( function() {
					$(this).parent().parent().parent().find(".gcnav").hide();
				});
				*/
			});
			
			
			$("#" + id_capa + " li a").click( function() {
				datos = $(this).attr("id").split("_");
				PRODUCTOS.rotaNoticias(datos[1], clase, id_capa);
			});

			$("#gc_noticia1").show();
			$(criterio + " li a").removeClass('activo');
			$(criterio + " .gci_1").addClass("activo");
			
			var totalFotoNoticias = $(criterio + " ul[class=galeria_contento_indice] li a").length;

			if(clase == 'modulo_player_contenido') {
				$(".modulo_player_contenido2").each(function() {
					$(this).removeClass("modulo_player_contenido2");
					$(this).addClass("modulo_player_contenido");
				});
			}



			$(criterio + " .ant").click( function() {
				$("." + clase + ' .galeria_contento .div_galeria_contento').filter(function() { return !$(this).is(":hidden") && $(this).attr("id") != 'gcc_video' }).each(function() {
					if($(this).attr("id").indexOf("gc_noticia") >= 0) {
						PRODUCTOS.indiceNoticiaActual = $(this).attr("id").replace("gc_noticia", "");
					} else if($(this).attr("id").indexOf("gcc_noticia") >= 0) {
						PRODUCTOS.indiceNoticiaActual = $(this).attr("id").replace("gcc_noticia", "");
					}
				});
				if(PRODUCTOS.indiceNoticiaActual == 1) {
					oculto = 1;
					indiceActivo = totalFotoNoticias;
				} else {
					oculto = PRODUCTOS.indiceNoticiaActual;
					indiceActivo = parseInt(PRODUCTOS.indiceNoticiaActual) - 1;
				}		
				if(clase == 'modulo_player_portada' || clase == 'modulo_player_articulo') {
					$("#gc_noticia" + oculto).fadeOut();
					$("#gc_noticia" + indiceActivo).fadeIn();
				} else if(clase == 'modulo_player_contenido') {
					$("#gcc_noticia" + oculto).fadeOut();
					$("#gcc_noticia" + indiceActivo).fadeIn();
				}
				$("." + clase + " .galeria_contento_indice li a").removeClass('activo');
				$("." + clase + " .gci_" + indiceActivo).addClass('activo');
				$(criterio + " li a").removeClass('activo');
				$(criterio + " .gci_" + indiceActivo).addClass('activo');
			});

			$(criterio + " .sig").click( function() {
				$("." + clase + ' .galeria_contento .div_galeria_contento').filter(function() { return !$(this).is(":hidden") && $(this).attr("id") != 'gcc_video' }).each(function() {
					if($(this).attr("id").indexOf("gc_noticia") >= 0) {
						PRODUCTOS.indiceNoticiaActual = $(this).attr("id").replace("gc_noticia", "");
					} else if($(this).attr("id").indexOf("gcc_noticia") >= 0) {
						PRODUCTOS.indiceNoticiaActual = $(this).attr("id").replace("gcc_noticia", "");
					}
				});
				
				if(PRODUCTOS.indiceNoticiaActual == totalFotoNoticias) {
					oculto = totalFotoNoticias;
					indiceActivo = 1;
				} else {
					oculto = PRODUCTOS.indiceNoticiaActual;
					indiceActivo = parseInt(PRODUCTOS.indiceNoticiaActual) + 1;
				}		
				if(clase == 'modulo_player_portada' || clase == 'modulo_player_articulo') {
					$("#gc_noticia" + oculto).fadeOut();
					$("#gc_noticia" + indiceActivo).fadeIn();
				} else if(clase == 'modulo_player_contenido') {
					$("#gcc_noticia" + oculto).fadeOut();
					$("#gcc_noticia" + indiceActivo).fadeIn();
				}
				if(id_capa == null) {
					$("." + clase + " .galeria_contento_indice li a").removeClass('activo');
					$("." + clase + " .gci_" + indiceActivo).addClass('activo');
				} else {
					$("#" + id_capa + " li a").removeClass('activo');
					$("#" + id_capa + " .gci_" + indiceActivo).addClass('activo');
				}
			});

		} else {
			$("." + clase + ' .galeria_contento .div_galeria_contento').filter(function() { return !$(this).is(":hidden") && $(this).attr("id") != 'gcc_video' }).each(function() {
				if($(this).attr("id").indexOf("gc_noticia") >= 0) {
					PRODUCTOS.indiceNoticiaActual = $(this).attr("id").replace("gc_noticia", "");
				} else if($(this).attr("id").indexOf("gcc_noticia") >= 0) {
					PRODUCTOS.indiceNoticiaActual = $(this).attr("id").replace("gcc_noticia", "");
				}
			});
			if(clase == 'modulo_player_portada' || clase == 'modulo_player_articulo') {
				$(criterio + " #gc_noticia" + PRODUCTOS.indiceNoticiaActual).fadeOut();	
				$(criterio + " #gc_noticia" + indice).fadeIn();	
			} else if(clase == 'modulo_player_contenido') {
				$(criterio + " #gcc_noticia" + PRODUCTOS.indiceNoticiaActual).fadeOut();	
				$(criterio + " #gcc_noticia" + indice).fadeIn();	
			}
			if(id_capa == null) {
				$("." + clase + " .galeria_contento_indice li a").removeClass('activo');
				$("." + clase + " .gci_" + indice).addClass('activo');
			} else {
				$("#" + id_capa + " .galeria_contento_indice li a").removeClass('activo');
				$("#" + id_capa + " .gci_" + indice).addClass('activo');
			}

			
		}

		$(".gcnav").each(function() {
			$(this).attr({ href: "javascript:void(0)"});
			//$(this).show();
		});
	}
};

PRODUCTOS.menuUsuarios = function() {
	if ($.cookie('queid_log') == '' || $.cookie('queid_log') == null) {
		$('.nav_usuarios').find('a').each(function() {
				$(this).attr('href', 'javascript:void(0)');
				$(this).click(function() {
						alert('Tienes que estar registrado para usar esta funcionalidad');
						var url = document.location.href;
						if(url.indexOf("foros.") == -1) {
							document.location.href = PRODUCTOS.edicion + '/registro/';
						} else {
							return false;
						}
					}
				);
			}
		);
	}
};

PRODUCTOS.menuHerramientas = function() {
	$('#votacion').find('a').each(function(i) {
			$(this).click(function(){
					HERRAMIENTAS.votarArticulo(i + 1);
				}
			);
		}
	);
	$('#votacion2').find('a').each(function(i) {
			$(this).click(function(){
					HERRAMIENTAS.votarArticulo(i + 1);
				}
			);
		}
	);
};

PRODUCTOS.maxmin = function() {
	$(".boton_despliega").click( function() {
		$(this).attr({ href: "javascript:void(0)"});
		if(!$(this).hasClass("btn_deson")) {
			$(this).parent().parent().parent().find(".mPC").slideDown("slow");
			$(this).addClass("btn_deson");
			
		} else {
			$(this).parent().parent().parent().find(".mPC").slideUp("slow");
			$(this).removeClass("btn_deson");
		}
	});
};

PRODUCTOS.loadXML = function(xml_string) {
	// Parche para IE
	if(window.ActiveXObject) {
		var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
		xmlDoc.loadXML(xml_string);
		xml = (xmlDoc.xml != "") ? xmlDoc : null;
	}
	else xml = (xml_string != "") ? xml_string : null;
	return xml;
}


$(document).ready(function() {
//	PRODUCTOS.menu();
//	PRODUCTOS.menuUsuarios();
	PRODUCTOS.menuHerramientas();
//	PRODUCTOS.maxmin();
});
