
//Galleria.loadTheme(home_url+'/wp-content/themes/AGENT/javascript/galleria/theme/galleria.classic.js');
 
////////////////////////////////////

$(document).ready(function(){

		// Truco android: '+$(window).scrollTop()+'px' funciona igual que 'translateY(0px)', pues no se respeta la traslación en position fixed, sin embargo si no se pone esta propiedad con algún valor el fixed no funciona. También estas propiedades deben quedar fuera de la función para darle más fluidez al contenido que sí se mueve al hacer scroll.
		ismobile=navigator.userAgent.match(/(iPad)|(iPhone)|(iPod)|(android)/i);
        if(ismobile)
        {
                var $areposicionar = $('header, footer').css('-webkit-transition', '-webkit-transform .2s ease-out');
				$("header a").css({"-webkit-transform":"translateX(0px)"}); // para que los links funcionen despues de que cambian su posición.
                
                reposicionar();
                
                $(window).scroll(function ()
                {
                        reposicionar();
                });
                
                function reposicionar()
                {
                        $areposicionar.css({'left':'-'+$(window).scrollLeft()+'px','-webkit-transform':'translateY('+$(window).scrollTop()+'px)'});
                }
        }	
	
	
	// logo con flash plugin, sólo en el home
	if(document.getElementById('slideshow')){
		
		if($.browser.msie) {
			/*
			$('#logo').flash({
				src: 'wp-content/themes/AGENT/images/logo.swf',
				width: 250,
				height: 153,
				bgcolor: "#000000"
			});
			$('#logo p').hide();*/
		}
	}
	
	// NEWS 
	$("#news p.news .thumb").css("cursor","pointer");
	$("#news p.news .item").hide();
	var segs = 500;
	var min  = 1;
	var max  = 10;
	var vel  = "normal";
	var itm  = " .item";
	var thb  = " .thumb";
	var itms = ".item";
	var thbs = ".thumb";
	var pnw  = "#news p.news";
	//onclick de noticias
	$('.news').each(function(cuenta){
		var num=cuenta+1;$(pnw+num).click(function(){var num=cuenta+1;$(thbs,this).fadeOut(vel);$(itms,this).delay(segs).fadeIn(vel);for(i=min;i<num;i++){$(pnw+i+itm).fadeOut(vel);$(pnw+i+thb).delay(segs).fadeIn(vel);}for(i=max;i>num;i--){$(pnw+i+itm).fadeOut(vel);$(pnw+i+thb).delay(segs).fadeIn(vel);}});
	});
	
	
	// INDEX CYCLE (slideshow del home)
	$("#slideshow").hide();
	setTimeout (function(){
	   if($(window).width()>1090&&$(window).height()>700){
			$('#slideshow img').css('width',804);
			$('#slideshow img').css('height',680);
			$('#slideshow').css('margin', '-10px 0 0 230px');
	   }; 
	   $("#slideshow").fadeIn('slow');
	   $("#slideshow").cycle({fx:'fade',speed:1000,timeout:4000,sync:0});
	},2700);
	
	if (!$.browser.msie && !navigator.userAgent.match(/Mobile/i)) { //si no es IE y tampoco un móvil
		// FADEIN (si no hay galería)
		if(!document.getElementById('gallery')){
			$("#content").hide();		
			$("#content").fadeIn('normal');		
		}
		
		// FADEOUT
		if(!document.getElementById('press')){ // Si no es la categoría PRESS, para permitir target='_blank'

			$("a").click(function(event){
				event.preventDefault();
				linkDestino = this.href;
				$("#content, #slideshow").fadeOut('normal', redireccionarPag);
				$("#html5video").fadeOut('normal');
			});
			
			function redireccionarPag() {
				window.location = linkDestino;
				setTimeout(function(){
				$("#content, #slideshow").fadeIn('normal');
				$("#html5video").fadeIn('normal');
				},3000);
			}

		}

	}

	
	// GALLERIA
	/*if(screen.width>=960) { //si es al menos un iPhone 4 //**desactivada**
		$('#gallery').galleria({image_crop:true,transition:'fade'});
		$('#gallery').css("border","1px solid #222");
		$('#gallery').hover(function(){
		$('#gallery').css("border","1px solid #444");
		},function(){
		$('#gallery').css("border","1px solid #222");
		});
	}*/
	
	// DESATURATE (cambio de imágenes b/n y color)
	if(!navigator.userAgent.match(/Mobile/i)) {	//si no estoy usando un navegador móvil
      $(function(){
        $(".press .thumb").bind("mouseenter mouseleave", function(event) {
            if (event.type == 'mouseenter')
            {
              $(".desaturate.color", this).fadeIn(500);
            }
            if (event.type == 'mouseleave')
            {
              $(".desaturate.color", this).fadeOut(500);
            }
          });
      });
	  /*
      $(function(){
        $(".mission .thumb").bind("mouseenter mouseleave", function(event) {
            if (event.type == 'mouseenter')
            {
              $(".desaturate.color", this).fadeIn(200);
            }
            if (event.type == 'mouseleave')
            {
              $(".desaturate.color", this).fadeOut(200);
            }
          });
      });
	  */
	}

	// Inserta videos
	var nombrevideo = $('#flarevideo').parent().attr('id');
	if(nombrevideo) { //si hay video en esta página y sabemos qué archivos hay que utilizar
			$('#html5video').html('HTML5 Video'); //inserta letrero de html5 video (flarevideo lo oculta si se usa versión flash)
			//if(screen.width>=640) { //si es iPhone4, iPad o superior, código avanzado de flarevideo
			if(screen.width>768) { //si es desktop
				
				jQuery(function($){
				  fv = $('#flarevideo').flareVideo({
					flashSrc: storage_url+'/wp-content/themes/AGENT/javascript/flarevideo/media/FlareVideo.swf',
					poster: storage_url+'/wp-content/uploads/videos/'+nombrevideo+'.jpg',
					autobuffer: true,
					preload: false,
					autoplay: true,
					width:640,
					height:360
				  });
				  fv.load([
					{
					  src:  storage_url+'/wp-content/uploads/videos/'+nombrevideo+'.mp4',
					  type: 'video/mp4'
					},
					{
					  src:  storage_url+'/wp-content/uploads/videos/'+nombrevideo+'.ogv',
					  type: 'video/ogg; codecs=\"theora, vorbis\"'
					}
				  ]);
				});
				
				$.browser.chrome = /chrome/.test(navigator.userAgent.toLowerCase());
				if($.browser.chrome){
					$(".flareVideo .controls").css({"position":"relative"});
					$(".videoagent").css("padding-bottom","41px");
				}
				
			} else { //pantallas pequeñas y/o sin soporte de video en navegador, código básico
				videotag = '<video class="video" id="videobasico_'+nombrevideo+'" width="640" height="360" poster="'+storage_url+'/wp-content/uploads/videos/'+nombrevideo+'.jpg" autoplay="autoplay" controls="controls" preload="false" autobuffer="autobuffer"><source src="'+storage_url+'/wp-content/uploads/videos/'+nombrevideo+'.mp4" type="video/mp4" /><source src="'+storage_url+'/wp-content/uploads/videos/'+nombrevideo+'.ogv" type="video/ogg" /></video>';
				$('#flarevideo').html(videotag); 
				document.getElementById('videobasico_'+nombrevideo).load();
				//document.getElementById('videobasico').play();
			}
		}
		
		if(document.getElementById('form-newsletter')) {
			new iContact();
		}
});

/**
 *	Para agregar a los que se suscriben al boletin de noticias
 *  a la lista de contactos de iContact
 */
function iContact() {
	var solicitud, formulario, checkbox, estado_checkbox = true, isIE = false;
	
	init();
	
	/**
	 * Agregar listeners a checkbox, y al formulario
	 */
	function init() {
		isIE 	   = navigator.userAgent.indexOf('MSIE') === -1 ? false : true;
		formulario = document.getElementById('wpcf7-f1-p16-o1').getElementsByTagName('form')[0];
		checkbox   = document.getElementById('form-checkbox-newsletter');
		
		isIE ? checkbox.attachEvent('onclick', clickAction) : checkbox.addEventListener('click', clickAction, false);
		
		
		isIE ? formulario.attachEvent('onsubmit', submitAction) : formulario.addEventListener('submit', submitAction, false);
		
		checkbox.className = "checked";
		
		if(!valorNewsletter()) {
			checkbox.className = "unchecked";
			estado_checkbox    = false;
		}
	}
	
	/**
	 *	Si se escogio recibir noticias o si no
	 */
	function valorNewsletter() {
		if(document.cookie.substr(document.cookie.indexOf('ans')+4, document.cookie.indexOf('ans')+9) == 'false') return false;
		return true;
	}
	
	/**
	 * Al hacer click en el span (checkbox) se cambia el estado
	 * o "value" y se muestra la palomita o se oculta
	 */
	function clickAction() {
		estado_checkbox = !estado_checkbox;
		
		estado_checkbox ? checkbox.className = "checked": checkbox.className = "unchecked";
	}
	
	/**
	 * Cuando se va a enviar el formulario se comprueba
	 * primero que los campos no esten vacios
	 * se envian los datos a iContact.php para que los
	 * agregue a la lista mediante una llamada a la api
	 */
	function submitAction(e) {
		
		if(!estado_checkbox) {
			document.cookie = 'ans=false';
			return;
		}
					
		isIE ? window.event.returnValue = false : e.preventDefault();
		
		var email  	   = document.getElementById('form-email').getElementsByTagName('input')[0].value;
		var nombre 	   = document.getElementById('form-name').getElementsByTagName('input')[0].value;
		
		if(nombre == '') {
			document.getElementById('form-name').getElementsByTagName('input')[0].focus();
			return;
		}
		
		if(email == '') {
			document.getElementById('form-email').getElementsByTagName('input')[0].focus();
			return;
		}
			
		isIE ? solicitud = new ActiveXObject('Microsoft.XMLHTTP') : solicitud = new XMLHttpRequest();
		
		solicitud.onreadystatechange = readystatechangeAction;
		
		solicitud.open('POST', 'iContact.php', true);
		
		solicitud.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		
		var datos = 'nombre='+nombre+'&email='+email;
		
		solicitud.send(datos);
		
		document.getElementById('form-submit').innerHTML = '<p>Your message is being sent</p>';
	}
	
	/**
	 * Una vez recibida la respuesta del servidor se envia el formulario
	 * Y se pone en true la cookie de opcion de newsletter
	 */
	function readystatechangeAction() {
		if(solicitud.readyState == 4) {
			document.cookie = 'ans=true';
			formulario.submit();
		}
	}
}
