//==============================================================================
// ############    Escuela Nacional de Entrenadores               ##############
// ############    (c)2010 Jose Mª Morales - www.serviline.net    ##############
// ############  Javascript basado en JQuery 1.3 - rev: 14/8/2010 ##############
//==============================================================================

//========== si la pagina se carga en un frame, se recarga =============

if (window.self != window.top)   window.top.location = window.self.location;


//============ Variables ==============

  var lang= "es"; // idioma por defecto (español)
	var pag = "10-inicio.html";  // Pagina que carga al inicio
  var header ='styles/head_entrenadores2.swf';

URL      = unescape(location.pathname);
URLfile  = URL.substring(URL.lastIndexOf('/')+1,URL.length); //elimina la raiz
URLquery = unescape(location.search.substring(1,location.search.length));
//  index.html?pag=12-localizacion.html&lang=eng  indica pagina a cargar e idioma

//============== Busca y extrae variables de la URL =================
if (URLquery!=""){        //  Ej: URL=path?var1=dato1&var2=dato2

    URLvars = URLquery.split ("&");

    for (i = 0; i < URLvars.length; i++) { 
            if (URLvars[i].indexOf("=")!=-1) {  
                vars = URLvars[i].split("=");
                eval ('var '+vars[0]+'="'+vars[1]+'"'); 
            }
    }
}//==================================================================
  // 'pag = pagina.html' -->  carga "pagina.html" 
  // 'lang = eng'       -->  idioma (si lang=eng carga "pagina_eng.html")

	var lastpage=pag;       // Ultima pagina cargada (evita recargarla)

                                              
                                              
$(document).ready(function(){  // ==============================================

  LOAD_page (pag)
 	$("ul.submenu").parent().append("<span></span>"); 


last_lista=""

   // Muestra y oculta los menús 
   $('ul.menu li:has(ul)').hover( 
      function(e) 
      { 
         $(this).find('ul').fadeIn('fast')  //.css({display: "block"}); 
      }, 
      function(e) 
      { 
         $(this).find('ul').fadeOut('fast') //.css({display: "none"}); 
      } 
   ); 

// captura clicks  del menu
	$("ul.menu a").each(function(){
	var href = $(this).attr("href");	//Guardamos el valor de href de cada enlace.

      $(this).click(function(){				//Cargamos el contenido del href.

            if (href!=lastpage  && href!="")  LOAD_page (href)
            return false;	//Para que no se redireccione
		  });
  }); 


 idm =""; // idioma 
/*
 if (lang=="eng") {   // cambio de idioma --------------

  header = header.replace(".swf","_eng.swf")
  
  $("#m10").html("Presentation")
  $("#m11").html("Introduction")
  $("#m12").html("Location")
  $("#m20").html("Activities")
  $("#m21").html("Events")
  $("#m22").html("Lectures")
  $("#m23").html("Courses and Seminars")
  $("#m24").html("Grants")
  $("#m25").html("Proyects")
  $("#m26").html("Awards")
  $("#m27").html("Sponsorships")
  $("#m30").html("Collaborations")
  $("#m40").html("Publications")
  $("#m50").html("Photo Gallery")
  $("#m60").html("Contact")
  $("#m70").html("Links")

  $("#lang").html('Spanish')
            .toggleClass('flag es')
            .attr("href","javascript:changeLANG('es')")
  idm ="_eng";
 } // -------------------------------- 
*/  
  flash(header) // inicia animacion en la cabecera
  $("#novedades").load('ofertas'+ idm +'.html')
  $("#destacadas").load('novedades'+ idm +'.html')

  $("#fecha").html(fecha(lang)).css({ 'color': "#666", 'font-size': "11px" });

}); // fin ready()  ============================================================


 ///////////////////////////////////////////////////////////////////

function LOAD_page (pag) {

lastpage  = pag;    // almacena la pagina en curso
//if (lang == "eng")    pag = pag.replace(".html","_eng.html")

var html="";
var contenidos = "#content .post";

$.ajax({
        url:    pag,
        async:  false, 
    //  complete:   alert("Proceso completado")
        success: function(datos){
                  html=datos
        },
        error: function(datos){
              //alert(datos.status) // 404 = pagina no encontrada
              //alert(datos.statusText) // Not Found
              html= "Página no disponible "
        }
})


  $(contenidos).fadeOut("normal", function(){
                   $(contenidos).html(html).fadeIn();      
             });


var URLnum = pag.substring(0,3);
var path  = "";

  if (URLnum=='10-' ) path="Presentación";

  if (URLnum=='20-' ) path="Preguntas Frecuentes"                      
   
  if (URLnum=='30-' ) path="Listado de cursos"; 
  if (URLnum=='31-' ) path="Curso Aerobic"; 
  if (URLnum=='32-' ) path="Curso Fitness"; 
  if (URLnum=='33-' ) path="Curso Culturismo";
  if (URLnum=='34-' ) path="Otros Cursos"; 

  if (URLnum=='40-' ) path="Ofertas"; 
  if (URLnum=='50-' ) path="Más información"; 
  if (URLnum=='60-' ) path="Área Alumnos"; 

/*
if (lang=="eng") {
  if (URLnum=='11-' ) path="Presentation -> Introduction";             
  if (URLnum=='12-' ) path="Presentation -> Location";
                            
*/

//$("#infobar .alignleft").html('-> '+ path);             

} // fin  LOAD_page()  ==========================================


function changeLANG(idioma){  // recarga pagina con el idioma seleccionado
    //  window.location="index.html?pag="+ lastpage +"&lang="+ idioma 
}

function flash(params) {    
  
  var dim ='width="972" height="132"';
//  var dim ='width="972" height="140"';
//  var params ='header2c.swf'

html='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000 " '+dim+
   ' codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab">'+  
   '<param name="movie" value="'+params+'" />'+
   '<param name="wmode" value="transparent" />'+
   '<embed wmode="transparent" '+dim+' src="'+params+'"'+
   ' type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />'+
    '</object>';

$("#header").html(html);
}//=================================================================




function fecha(lang) {

  var hoy=new Date()
  var dia_semana=new Array("Domingo","Lunes","Martes","Miércoles","Jueves","Viernes","Sabado")
  var dia_mes=new Array("Enero","Febrero","Marzo","Abril","Mayo","Junio","Julio","Agosto","Septiembre","Octubre","Noviembre","Diciembre")
  var of=" de ";

if (lang=="eng") {
  var dia_semana=new Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday")
  var dia_mes=new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December")
  var of=" ";
}
  
      var year  = hoy.getYear()  // año (OJO: NS cuenta desde 1900)
        if (year < 1000)  year+=1900 // corrección para NS
      var day   = hoy.getDay()   // dia de la semana (de 0 a 6)
      var month = hoy.getMonth() // mes del año (de 0 a 11)
      var daym  = hoy.getDate()  // dia del mes (de 1 a 31)
        if (daym<10)  daym="0"+daym

return  dia_semana[day] +", "+ daym +of+ dia_mes[month] +of+ year

}//==================================================================



//########## Comprobacion DATOS del formulario ############
function validate_form() {
    
     validity = true;
    
     if (document.form1.nombre.value == "") {
      alert('Por favor, introduzca su nombre!');
      validity = false;
     }
     if ((document.form1.telefono.value == "") ) {
      if (confirm("¿Quiere incluir su telefono?")){
       document.form1.telefono.focus();
       validity = false;
        }  
     }
   /* */
    
 //============= COMPRUEBA EL EMAIL ==================
     if (document.form1.email.value != "") {
         arrPos  = document.form1.email.value.indexOf('@');
         puntPos = document.form1.email.value.lastIndexOf('.');
         L = document.form1.email.value.length
    	if ( (arrPos<1  || arrPos>L-5)  ||  (puntPos<L-4  || puntPos>L-3 ) ||  puntPos-arrPos<=2 ) {
    	     alert("E-mail Incorrecto");
    	     document.form1.email.value="";
    	     document.form1.email.focus();
    		 return false;
    		}   
    	}
    else{
      alert('Por favor, introduzca su e-mail!');
    	document.form1.email.focus();
    	return false;
       }
    // ==========================================
     
    if (validity) enviar()
     //return validity;
}

function enviar(){

    $.post("mail.php",
     {Nombre  : document.form1.nombre.value,
      Email   : document.form1.email.value,
    //   Empresa : document.form1.empresa.value,
//       Direccion: document.form1.direccion.value,
//       Localidad: document.form1.localidad.value,
//       Provincia: document.form1.provincia.value,
//       CPostal: document.form1.CP.value,
//       Pais : document.form1.pais.value,
       Tfno : document.form1.telefono.value,
//       Fax  : document.form1.FAX.value,
//      Mailto  : "jmorales@serviline.es",   // REVISAR, no va
//      Mailto  : "info@bio-natura.net",
      Mensaje : document.form1.mensaje.value
    },  function(msg){
        if (msg) {
            alert(msg); // Devuelve mensaje del script PHP
            document.form1.reset(); // Borra campos
        }else {
            alert("Se ha producido un error!\n\nEl mensaje no ha sido enviado")
        }  
    });
  
}// fin envio de datos ====================================


function validate_form2() {
    
     validity = true;
    
     if (document.form2.nombre.value == "") {
      alert('Por favor, introduzca su nombre!');
      validity = false;
     }
     if ((document.form2.telefono.value == "") ) {
      if (confirm("¿Quiere incluir su telefono?")){
       document.form2.telefono.focus();
       validity = false;
        }  
     }
    
 //============= COMPRUEBA EL EMAIL ==================
     if (document.form2.email.value != "") {
         arrPos  = document.form2.email.value.indexOf('@');
         puntPos = document.form2.email.value.lastIndexOf('.');
         L = document.form2.email.value.length
    	if ( (arrPos<1  || arrPos>L-5)  ||  (puntPos<L-4  || puntPos>L-3 ) ||  puntPos-arrPos<=2 ) {
    	     alert("E-mail Incorrecto");
    	     document.form2.email.value="";
    	     document.form2.email.focus();
    		 return false;
    		}   
    	}
    else{
      alert('Por favor, introduzca su e-mail!');
    	document.form2.email.focus();
    	return false;
       }
  // ==========================================
     
    if (validity) enviar2()
     //return validity;
}

function enviar2(){

    $.post("mail.php",
     {Nombre    : document.form2.nombre.value,
      Apellidos : document.form2.apellidos.value,
      Direccion : document.form2.direccion.value,
//       Localidad: document.form1.localidad.value,
      Provincia : document.form2.provincia.value,
      CPostal   : document.form2.CP.value,
      Pais      : document.form2.pais.value,
      Tfno      : document.form2.telefono.value,

      Email     : document.form2.email.value,
      Curso     : document.form2.curso.value,
//      Mailto    : "jmorales@serviline.es"   // REVISAR, no va
//      Mailto  : "info@bio-natura.net"
      Mensaje : document.form2.mensaje.value
    },  function(msg){
        if (msg) {
            alert(msg); // Devuelve mensaje del script PHP
            document.form2.reset(); // Borra campos
        }else {
            alert("Se ha producido un error!\n\nEl mensaje no ha sido enviado")
        }  
    });
  
}// fin envio de datos ====================================
