var GENERAL = {};

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


GENERAL.menu = function() {
	
	/* Menu modificado para este proyecto */

	var urlPath = jQuery.url.attr('path');

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

	switch(urlPath) {
		case '/':
			$("img[id=menu_inicio]").attr('src', '/images/txt_inicio_sel.png');
			break;
		case '/instrucciones/':
			$("img[id=menu_instrucciones]").attr('src', '/images/txt_instrucciones_sel.png');
			break;
		case '/retos/':
			$("img[id=menu_retos]").attr('src', '/images/txt_los_retos_sel.png');
			break;
		case '/premios/':
			$("img[id=menu_premios]").attr('src', '/images/txt_premios_sel.png');
			break;
		case '/participa/':
			$("img[id=menu_participa]").attr('src', '/images/txt_participa_sel.png');
			break;
		case '/bases-legales/':
			break;
		case '/politica-privacidad/':
			break;
		case '/accede/':
			$("img[id=menu_accede]").attr('src', '/images/txt_accede_sel.png');
			break;
		case '/videos/':
			break;
		case '/buscador/':
			break;
		case '/participantes/':
			$("img[id=menu_participantes]").attr('src', '/images/txt_participantes_sel.png');
			break;
		case '/politica-privacidad-participa/':
			break;
		case '/politica-privacidad-grados/':
			break;
		default:
			$("img[id=menu_inicio]").attr('src', '/images/txt_inicio_sel.png');
			break;
	}

};

GENERAL.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;
}


GENERAL.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;
};

GENERAL.fechaValida = function(valor) {
	var formatoFechaReg = GENERAL.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;
};

GENERAL.horaValida = function(valor) {
	var formatoHoraReg =  GENERAL.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;
};

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

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

GENERAL.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]);
					$.facebox('<p><strong>AVISO PARA LA INSCRIPCIÓN</strong></p><p>No has rellenado el campo <strong>' + datosCheck[1] + '</strong></p>');
					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);
					$.facebox('<p><strong>AVISO PARA LA INSCRIPCIÓN</strong></p><p>El campo <strong>' + datosCheck[1] + '</strong> tiene que ser numérico.' + texto_explicativo + '</p>');
					campoForm.focus();
					return false;
				}
			}
			if((datosCheck[0].indexOf('email') != -1) && (campoForm.value != "")) {
				if(!GENERAL.emailValido(campoForm.value)) {
					//alert('El campo ' + datosCheck[1] + ' tiene que ser un email');
					$.facebox('<p><strong>AVISO PARA LA INSCRIPCIÓN</strong></p><p>El campo <strong>' + datosCheck[1] + '</strong> tiene que ser un email</p>');
					campoForm.focus();
					return false;
				}
			}
			if((datosCheck[0].indexOf('fecha') != -1) && (campoForm.value != "")) {
				if(!GENERAL.fechaValida(campoForm.value)) {
					//alert('El formato del campo ' + datosCheck[1] + ' no es válido');
					$.facebox('<p><strong>AVISO PARA LA INSCRIPCIÓN</strong></p><p>El formato del campo <strong>' + datosCheck[1] + '</strong> no es válido</p>');
					campoForm.focus();
					return false;
				}
			}
			if((datosCheck[0].indexOf('hora') != -1) && (campoForm.value != "")) {
				if(!GENERAL.horaValida(campoForm.value)) {
					//alert('El formato del campo ' + datosCheck[1] + ' no es válido');
					$.facebox('<p><strong>AVISO PARA LA INSCRIPCIÓN</strong></p><p>El formato del campo <strong>' + datosCheck[1] + '</strong> no es válido</p>');
					campoForm.focus();
					return false;
				}
			}
			if(datosCheck[0].indexOf('checkbox') != -1) {
				if(campoForm.checked == false) {
					//alert('No has rellenado el campo ' + datosCheck[1]);
					$.facebox('<p><strong>AVISO PARA LA INSCRIPCIÓN</strong></p><p>No has rellenado el campo <strong>' + datosCheck[1] + '</strong></p>');
					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]);
					$.facebox('<p><strong>AVISO PARA LA INSCRIPCIÓN</strong></p><p>No has rellenado el campo <strong>' + datosCheck[1] + '</strong></p>');
					return false;
				}
			}
			if(datosCheck[0].indexOf('select') != -1) {
				if(campoForm.selectedIndex == 0) {
					//alert('No has rellenado el campo ' + datosCheck[1]);
					$.facebox('<p><strong>AVISO PARA LA INSCRIPCIÓN</strong></p><p>No has rellenado el campo <strong>' + datosCheck[1] + '</strong></p>');
					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]);
					$.facebox('<p><strong>AVISO PARA LA INSCRIPCIÓN</strong></p><p>No has rellenado el campo <strong>' + datosCheck[1] + '</strong></p>');
					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');
					$.facebox('<p><strong>AVISO PARA LA INSCRIPCIÓN</strong></p><p>El campo <strong>' + datosCheck[1] + '</strong> no es válido</p>');
					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');
					$.facebox('<p><strong>AVISO PARA LA INSCRIPCIÓN</strong></p><p>El campo <strong>' + datosCheck[1] + '</strong> tiene que tener al menos <strong>' + limite + '</strong> caracteres</p>');
					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');
					$.facebox('<p><strong>AVISO PARA LA INSCRIPCIÓN</strong></p><p>El campo <strong>' + datosCheck[1] + '</strong> tiene que como máximo <strong>' + limite + '</strong> caracteres</p>');
					campoForm.focus();
					return false;
				}
			}
			if(datosCheck[0].indexOf('foto') != -1) {
				if((campoForm.value != "") && !GENERAL.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.');
					$.facebox('<p><strong>AVISO PARA LA INSCRIPCIÓN</strong></p><p>El formato de la <strong>foto</strong> no es correcta. Verifique que es un <strong>JPEG</strong> o un <strong>GIF</strong> o que el <strong>nombre no tiene acentos, espacios o caracteres extraños</strong>.</p>');
					campoForm.focus();
					return false;
				}
			}
			if(datosCheck[0].indexOf('mp3') != -1) {
				if((campoForm.value != "") && !GENERAL.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.');
					$.facebox('<p><strong>AVISO PARA LA INSCRIPCIÓN</strong></p><p>El formato del <strong>mp3</strong> no es correcto. Verifique que es un <strong>MP3</strong> o que el <strong>nombre no tiene acentos, espacios o caracteres extraños</strong>.</p>');
					campoForm.focus();
					return false;
				}
			}
			if(datosCheck[0].indexOf('acepto') != -1) {
				if(campoForm.checked == false) {
					//alert('Tienes que aceptar las condiciones');
					$.facebox('<p><strong>AVISO PARA LA INSCRIPCIÓN</strong></p><p>Tienes que aceptar <strong>las bases legales</strong> y <strong>política de privacidad</strong>.</p>');
					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.');
					$.facebox('<p><strong>AVISO PARA LA INSCRIPCIÓN</strong></p><p>El <strong>formato del precio</strong> no es correcto. El formato correcto es 1000,11.</p>');
					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.');
					$.facebox('<p><strong>AVISO PARA LA INSCRIPCIÓN</strong></p><p>El campo <strong>' + datosCheck[1] + '</strong> no coincide.</p>');
					campoForm.focus();
					return false;
				}
			}
		}
	}
	return true;
};

GENERAL.envFormFichero = function (frm, funcion) {
	if(funcion == null || funcion == '') {
		funcion = GENERAL.respEnvFormFichero;
	}
	if(GENERAL.checkForm(frm)) {
		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();
	}
};

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

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

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

GENERAL.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;
}

GENERAL.abrirPopup = function (url) {
	window.open(url, 'condiciones', 'height=300,width=460');
}

GENERAL.personalizar = function() {
	
	//		retoieuniversity.elcorreo.com
	//  	www.retoieuniversity.com
	
	var urlPath = jQuery.url.attr('host');

	arrDatos = urlPath.split(".");
	
	if(arrDatos[1] != 'retoieuniversity' && arrDatos[1] != 'vocento' && arrDatos[1] != '' && arrDatos[2] != ''){
		$(".personalizacion").append(
		 $("<p/>").append(
							$("<a/>")
							.attr("href","http://www." + arrDatos[1] + "." + arrDatos[2])
							.attr("target","_blank")
							.attr("title",arrDatos[1] + "." + arrDatos[2])
							.append(
									$("<img>")
									.attr("src","/images/personalizacion/" + arrDatos[1] + ".gif")
									.attr("alt",arrDatos[1] + "." + arrDatos[2])
									)
							)
		);
	}
};

$(document).ready(function() {
	GENERAL.menu();
	GENERAL.menuHerramientas();
	GENERAL.personalizar();	
});
