document.observe('dom:loaded', function() {
  // Cargar twitter widget
  /* var twitterWidget = $('cronos_twitter') || $('nota_twitter');
  if(twitterWidget) {
    var twitterCont = $('cronos_int') || $('columna_derecha');
    if($('cronos_int')) {
      twitterCont.insert({ bottom: twitterWidget.show() });
    } else {
      twitterCont.insert({ top: twitterWidget.show() });
    }
  } */

  var compartirRedes = $('share_twitter_facebook');
  if(compartirRedes) {
    var compartir = $('share');
    compartirRedes.insert(compartir.show());
  }

  var boton = $('video_btnplay');
  var anteriores = $('videos_anteriores');
  if(boton) {
    observarClicksVideo(true);
  } else if(anteriores) {
    observarClicksVideo(false);
  }

  var hemeroteca = $('BuscarForm');
  if(hemeroteca) {
    observarSubmitHemeroteca(hemeroteca);
  }

  var opacidad = $('principal_opacidad');
  if(opacidad) {
    var height = opacidad.clientHeight;
    var top = parseInt(opacidad.getStyle('top'));
    top -= (height - 60);
    opacidad.setStyle({
      setTop: top
    });

    if(Prototype.Browser.IE) {
      var js = $$('.jet_set');
      if (js.length > 0) {
        js.each(function(e) {
          e.setStyle({
            width: 221
          });
        });
      }

      var df = $('deportes_nota_titulo');
      if(df) {
        df.setStyle({
          width: 98
        });
      }

      var ni = $('nota_imagen');
      if(ni) {
        ni.setStyle({
          width: 578
        });
      }
    }
  }

  // NOTA
  var videoNota = $('video_nota');
  if(videoNota) {
    var link = $('video_nota_link');
    var video = link.readAttribute('data-video');
    var img = link.readAttribute('data-imagen');
    var tipo = link.readAttribute('data-tipo');
    var local = link.readAttribute('data-local');
    var rt;
    if(document.URL.match(/localhost/)) {
      rt = {
        root: 'webroot/files/',
        rootimg: 'webroot/img/',
        rootvid: '../vid/',
        nota: true
      }
    } else {
      rt = {
        root: '/files/',
        rootimg: '/assets/notas/minis/',
        rootvid: local == 'true' ? 'http://tiempo.com.mx/assets/notas/video/' : 'http://puentelibre.mx/assets/notas/video/',
        nota: true
      }
    }
    link.observe('click', function(e) {
      insertarVideo(tipo, videoNota, video, img, '', rt);
      e.stop();
    });
  }

  // CLIMA
  var clima = $('clima_texto_imagen');
  if(clima) {
    var urlClima = clima.readAttribute('data-root') + 'clima';
    new Ajax.Request(urlClima, {
      method: 'get',

      onSuccess: function(r) {
        clima.update(r.responseText);
      }
    });
  }
});

function observarClicksVideo(play) {

  // Observar play solo si esta presente
  if(play) {
    // botones de play
    var play_buttons = new Array(
      $$('#video_btnplay a')[0],
      $$('#video_principal_marco a')[0]
      );

    // al hacer click en un boton de play
    play_buttons.each(function(button) {
      button.observe('click', function(event) {
        playVideo(event.target, false);
        event.stop();
      });
    });
  }
  // videos anteriores
  var anteriores = $$('.anterior img');

  // al hacer click en un video anterior
  anteriores.each(function(ant){
    ant.observe('click', function(event) {
      playVideo(event.target, true);
      event.stop();
    });
  });
}

function dejarDeObservar() {
  // videos anteriores
  var anteriores = $$('.anterior img');

  anteriores.each(function(ant){
    ant.stopObserving();
  });
}

// funcion que actualiza el video principal
function playVideo(target, actualizarLista) {

  var id = parseInt(target.id) || '';
  var url, root, rootimg, rootvid;
  if(document.URL.match(/localhost/)) {
    url = '/tiempo_nuevo';
    root = 'webroot/files/';
    rootimg = 'webroot/img/';
    rootvid = '../vid/';
  } else {
    url = '';
    root = '/files/';
    rootimg = '/assets/notas/fotos/';
    rootvid = 'http://tiempo.com.mx/videos/';
  }
  url += '/video/' + id;
  var vp = 'video_principal';

  new Ajax.Request(url, {
    method: 'get',
    encoding: 'iso-8859-1',

    onSuccess: function(r) {
      var toRemove = new Array(
        $('video_btnplay_1'),
        $('video_btnplay'),
        $('video_principal_marco'),
        $('video_principal_opacidad')
        );
      // se quitan los elementos que estan en la posicion del video principal
      toRemove.each(function(e) {
        if(e)
          e.remove();
      });

      // Muestra el elemento del titulo y descripcion
      var tit_container = $('tit_video');
      tit_container.show();

      // tipo de video
      var tipo = leerParam('tipo', r.responseText);

      // lectura de parametros
      var tit = leerParam('tit', r.responseText);
      var desc = leerParam('desc', r.responseText);

      tit_container.update(
        '<span class="titulo">' + tit + '</span>' +
        '<br />' +
        '<span class="descripcion">' + desc + '</span>'
        );

      var video = leerParam('vid', r.responseText); // nombre archivo video
      var img = leerParam('img', r.responseText); // nombre archivo foto
      var embed = leerParam('embed', r.responseText); // contenido del embed

      var rt = {
        root: root,
        rootimg: rootimg,
        rootvid: rootvid
      }

      // insertar video
      insertarVideo(tipo, vp, video, img, embed, rt);

      // se actualiza la lista de los videos anteriores
      if(actualizarLista) {
        var lista = $('videos_anteriores'); // Lista de videos
        var lst = leerParam('lst', r.responseText); // Respuesta de videos
        dejarDeObservar();
        lista.update(lst);
        observarClicksVideo(false);
      }
    },

    onFailure: function() {
      alert('Error');
    }
  });
}

// Lee algun parametro mandado por el Ajax.Request
function leerParam(param, respuesta) {
  return respuesta.substring(respuesta.indexOf(param + '=') + param.length + 1, respuesta.indexOf('@@' + param));
}

// Al hacer click en buscar notas en hemeroteca
function observarSubmitHemeroteca(forma) {
  forma.observe('submit', function() {
    var url = 'buscar';
    var busca = this.busca.value;
    var dia = ceroIzquierda(this.diaDay.value);
    var mes = ceroIzquierda(this.mesMonth.value);
    var anio = ceroIzquierda(this.anioYear.value);
    url += "/" + busca + "/" + anio + "/" + mes + "/" + dia + '/1';
    // Buscar las notas en hemeroteca
    buscarNotasHemeroteca(url);
  });
}

// Llamada a funcion buscar por medio de Ajax
function buscarNotasHemeroteca(url) {
  new Ajax.Request(url, {
    method: 'get',
    encoding: 'utf8',

    onLoading: function() {
      $('loader').update('<img src="webroot/img/ajax-loader.gif" />');
    },

    onSuccess: function(r) {
      $('resultados').update(r.responseText);
      $('loader').update('');

      // Observar los clicks en anterior y siguiente en resultados de hemeroteca
      var paginaSiguiente = $('pagina_siguiente');
      var paginaAnterior = $('pagina_anterior');
      if(paginaSiguiente) {
        // Click en siguiente
        paginaSiguiente.observe('click', function(e) {
          var pagSig = this.readAttribute('data-pagina');
          var urlSig = url.substr(0, url.indexOf('/', (url.length - (pagSig.length + 1)))) + '/' + pagSig;
          buscarNotasHemeroteca(urlSig);
          e.stop();
        });
        // Click en anterior
        paginaAnterior.observe('click', function(e) {
          var pagAnt = this.readAttribute('data-pagina');
          var urlAnt = url.substr(0, url.indexOf('/', (url.length - (pagAnt.length + 1)))) + '/' + pagAnt;
          buscarNotasHemeroteca(urlAnt);
          e.stop();
        });
      }
    },

    onFailure: function() {
      $('resultados').update('Lo sentimos, se ocasionó un error al momento de la búsqueda');
      $('loader').update('');
    }
  });
}

// Poner cero al principio de cadena
function ceroIzquierda(numero) {
  numero = numero.toString().length == 0 ? "00" : numero.toString();
  return (numero.length < 2) ? ("0" + numero) : numero;
}

// Se agrega el video al elemento vp dependiendo del tipo
// video es el nombre del archivo del video
// img es el nombre del archivo de la foto
// rt es un hash { root: donde esta el reproductor, rootimg: donde esta la foto, rootvid: donde esta el video }
function insertarVideo(tipo, vp, video, img, embed, rt) {
  var width = rt.nota ? 245 : 300;
  var height = rt.nota ? 200 : 245;
  if(tipo == 'flash' || tipo == 'flv' || tipo == 'mp4') {
    var so = new SWFObject(rt.root + '/player.swf','mpl',width,height,'9');
    so.addParam('allowfullscreen','true');
    so.addParam('allowscriptaccess','always');
    so.addParam('wmode','opaque');
    so.addVariable('backcolor','333333');
    so.addVariable('frontcolor','FFFFFF');
    so.addVariable('image', rt.rootimg + 'vid_thumb/' + img);
    so.addVariable('autostart', true);
    so.addVariable('file', rt.rootvid + video);
    so.write(vp);
  } else if (tipo == 'wmv' || tipo == 'wma' || tipo == 'mpg') {
    $(vp).update('<embed type="application/x-mplayer2"' +
      'pluginspage="http://www.microsoft.com/Windows/MediaPlayer/"' +
      'name="mediaplayer1" autostart=1 width="'+width+'" height="'+height+'"' +
      'transparentstart="1" SHOWSTATUSBAR="0" loop="0" controller="true"' +
      'src="' + rt.rootvid + video.replace('%20', ' ') + '" stretchToFit="true" />');
  } else if(tipo == 'embed') { // se actualiza el video con el embed
    $(vp).update(embed);
  }
}
