var total_w;
var noScroll=false;
var h_actual;
var one_time=true;
var is_touch_device=false;
var myScroll;
$(function(){
	
		 is_touch_device = (/iPhone|iPod|iPad|android/i).test(navigator.userAgent);
		 
		 
		 
		 var v=400;
			// iframes
			$("iframe").height($("body").height()-$("#header").height()-$("#footer").height());
	// menu home
	$("#gallery_home > li").bind("mouseup mousedown mouseover mouseout",function(evt){
	$li=$(this);
	if (!$li.hasClass("no-link")){
		if (evt.type=="mouseup"){
			$li.css("margin-top","10px");
			$(this).children("a").click();
			}
		else if (evt.type=="mousedown")
			$li.css("margin-top","15px");
		else if (evt.type=="mouseover"){
			$li.css("margin-top","10px");
			$li.find(".minisite").addClass("act");
		
				if (!is_touch_device){
					$li.find(".minisite > div").show();
					//$li.find(".cartel").fadeTo(0, 0);
				}
			
		}
		else if (evt.type=="mouseout"){
			$li.css("margin-top","15px");
			$li.find(".minisite").removeClass("act");
			
				if (!is_touch_device){
					$li.find(".minisite > div").hide();
					//$li.find(".cartel").fadeTo(0, 1);
				}
			
		}
	}
	});


	
	$(".no-link").find("a").click(function(evt){
		evt.preventDefault();
	});

	
	
	//menu principal
		/*$('#menu li').each(function(){
			var w = $(this).innerWidth();
			if ($(this).find('ul')){
				$(this).find('ul').css('width',w+'px');
			}
		})*/
			
	// PAGE PROMOCION
		
		
		//slideshow
		
		
		calcular_width();
		$("#slider").find("img:eq(0)").each(function() {
			
			if ($(this)[0].complete) {
				colocar_slider();
					
			} else {
				$(this).load(function(){
					colocar_slider();
				});
			}
		});
			
			
			
		
		// Ocultamos mapa
		//$("#maps").height($("#content-top").height());
		
		
		$("#maps_wrapper").hide();
		$("#video_wrapper").hide();
		
		
		//menus
		var ul_menu=$(".promocion").find("ul#menu");
		var ul_planos=$(".promocion").find("ul#planos");
		
		// inizializamos menus
		ul_menu.find("span.act").hide();
		ul_planos.find("span.act").hide();
		colocar(ul_menu.children().first());
		colocar(ul_planos.children().first());
		
		// menu principal
		ul_menu.children("li").children("span").children("a").click(function(evt){
			//evt.preventDefault();
			var $li=$(this).parents("li");
			colocar($li);
			$actual=$("#contents").children("div:eq("+$li.index()+")");
			$actual.siblings().fadeOut(200,function(){$actual.fadeIn(200,mover_scroll)});
			
			
			$("#video_wrapper > .video-js-box").html("");
			
			
			if ($li.index()==1 && $("#loc_lat").val()){
				
				if (!is_touch_device)
					$('html,body').animate({scrollTop: 0}, 400);
				
				
				var cadena="";
				
				var zoom=$("#loc_zoom").val();
					if (!zoom)
						zoom="15";
						
					$("#maps_wrapper,#iframe").height(h_actual).show().siblings().hide();
					
					$("#iframe").attr("src",absPath+"/maps.php?points_lat="+$("#loc_lat").val()+"&points_lng="+$("#loc_lng").val()+"&center="+$("#loc_lat").val()+"$"+$("#loc_lng").val()+"$"+zoom);
					/*$("#iframe").load(function(){
						$("#iframe").find("#map_canvas").height(h_actual);
					});*/
					
				
			}  else if ($li.hasClass("video")){
				$('html,body').animate({scrollTop: $(".colmask").position().top-50}, 400);
				mostrarVideoUI(false);
			
			} else
			{
				if (!is_touch_device && !$li.hasClass("no-scroll"))
					$('html,body').animate({scrollTop: $(".colmask").position().top-50}, 400);
				$("#slider").show().siblings().hide();
				$("#slider1prev,#slider1next").show()
			}
				 
	
		});
		var one_time=true;
		$(".video_link > a").bind("click touchend",function(evt){
			evt.preventDefault();
			mostrarVideoUI(true);
					
				
				
			
		});
		
		$("#scrollThumbs").find("li").bind("click mouseenter mouseleave",function(evt){
			
			if (evt.type=="click" || evt.type=="touchend"){
				mostrarVideo($(this).data("title"),$(this).data("poster"),true);
			} else if (evt.type=="mouseenter"){
				$(this).addClass("act");
			} else if (evt.type=="mouseleave"){
				$(this).removeClass("act");
			}
		});
		
			
		ul_menu.children("li.li_planos").children("span").children("a").click(function(evt){
			
			ul_planos.show('slow', function() {
				ul_planos.find("a:first").click();
			})
			
		});
		
		// menu planos
		ul_planos.find("a").click(function(evt){
			
			//evt.preventDefault();
			var $li=$(this).parents("li");
			colocar($li);
			
			var plano_pdf=$("#"+$(this).attr("title"));
			var plano_title=$(this).attr("title");
			
			
			$img=$("<img style='width:100%;' src='"+$(this).attr("rel")+"'/>").load(function(){
			//$("#contents").children("div#plano").fadeIn(200).html($img).siblings().fadeOut(100);
			$actual=$("#contents").children("div#plano");
			$actual.siblings().fadeOut(200,function(){ $actual.html($img).fadeIn(200,mover_scroll())});
			if (plano_pdf.length>0) 
				$actual.prepend("<div class='download'><div></div><a target='_blank' href='"+plano_pdf.val()+"'>DESCARGAR PLANO "+plano_title+"</a></div>");
				
			});
			
			
		});
		
		
		
		//inicializamos el primero
		
		
		
		//contacto
		$("#bt_contacto").click(function(evt){
			//evt.preventDefault();
			//$("#contents").children("div#contacto").fadeIn(200).siblings().fadeOut(100);
			$actual=$("#contents").children("div#contacto")
			$actual.siblings().fadeOut(200,function(){ $actual.fadeIn(200,mover_scroll)});
			
			mover_scroll();
			
		});
		
		// resize
		$(window).resize(function() {
		
  			calcular_width();
			$("#iframe").height(h_actual).contents().find("#map_canvas").height(h_actual);
			if (myScroll)
				myScroll.refresh();
				
			//$("video").css("height","100%");
				
		});
		
		$(window).scroll(function(evt) {
				
  				//if (noScroll)
					evt.preventDefault();
		});
		
		
		
		/*if (is_touch_device){
			
			myScroll = new iScroll('main_scroll',{ bounce:false, momentum: true });
			//$('body').bind('touchmove',function(evt){evt.preventDefault();}); 
			
			
		}*/
		
		
			
			
	
	// END -- PAGE PROMOCION
});
var first_time=true;
function mostrarVideoUI(scroll){

	
				setTimeout(function(){
					$("#video_wrapper").show().siblings().hide();	
					
					
					$('#scrollThumbs').jScrollPane({verticalDragMaxHeight:28,autoReinitialise:true});

				},400);
				
				
				if (scroll){
					if (is_touch_device)
						$('html,body').scrollTop=0;
					else
						$('html,body').animate({scrollTop: 0}, 400);
				}
				
				if (first_time){
				setTimeout(function(){
					mostrarVideo($("#scrollThumbs").find("li:eq(0)").data("title"),$("#scrollThumbs").find("li:eq(0)").data("poster"),false);
				},600);
				}
	
}

function mostrarVideo(title,pathImage,play){
var mp4=absPath+"/videos/"+title+".mp4";
var ogv=absPath+"/videos/"+title+".ogv";
var image=pathImage;

				$("#video_wrapper > .video-js-box").html('<video data-ratio="1.755" id="video-1" class="video-js" width="auto" height="100%" controls="controls" preload="auto" poster="'+image+'"><source src="'+mp4+'" type="video/mp4; codecs=\"avc1.42E01E, mp4a.40.2\"" /><source src="'+ogv+'" type="video/ogg; codecs=\"theora, vorbis\""/><object id="flash_fallback_1" class="vjs-flash-fallback" width="568" height="320" type="application/x-shockwave-flash" data="http://releases.flowplayer.org/swf/flowplayer-3.2.1.swf"><param name="movie" value="http://releases.flowplayer.org/swf/flowplayer-3.2.1.swf" /><param name="allowfullscreen" value="true" /><param name="flashvars" value=\'config={"playlist":["'+image+'", {"url": "'+mp4+'","autoPlay":false,"autoBuffering":true}]}\' /><img src="'+image+'" width="568" height="320" alt="Poster Image" title="No video playback capabilities." /></object></video>');
				
					VideoJS.setupAllWhenReady();
					if (play)
						VideoJS.setup("video-1",{controlsHiding:true,autoplay:true}).play();
					else
						VideoJS.setup("video-1",{controlsHiding:true,autoplay:false});
					
					calcular_width();
}

				

				


function colocar($li){
	$li.children().first().show().siblings().hide();
	$li.siblings().each(function(){
		$(this).children().first().hide().siblings().show();
	});
}

function calcular_width(){
	
			count=$("#slider").find("img").length;
			//$(".promocion").find("ul#menu").find("a").first().click();
			total_w=$("#content-top").width();
			ratio=$("#content-top").width()/total_w;
			
			$ul=$("#slider").children("ul").stop(true,true);
			var new_margin=parseInt($ul.css("margin-left"))*ratio;
			h_actual=total_w/3.04761905;
			$("#slider").css("width",total_w).find("img,li").css("width",total_w).height(h_actual);
			$ul.css("width",total_w*count).css("margin-left",new_margin);
			// height = width * ratio (1280 / 420 = 3,04761905)
				$("#content-top,#slider,#scrollThumbs,video,.video-js-box").height(h_actual);
	
			$(".vjs-controls,.video-js-box").css("width",h_actual*$("video").data("ratio")+"px");
			
		
}

function mover_scroll(){
	noScroll=true;
	//$('html,body').animate({ scrollTop: $(".colmask").offset().top - $("#header").height()-50 }, { duration: 1000},function(){noScroll=false; });
	if (myScroll)
				myScroll.refresh();
}

function colocar_slider(){
	$("#slider").easySlider({
				auto: false,
				continuous: true,
				nextId: "slider1next",
				prevId: "slider1prev",
				prevText: "",
				nextText: "",
				pause:5000
			});
	$("#slider").css("opacity","1");
	
	
}

/* contact form */
	$(function(){				
			
		$('#contact_form').submit(function(e){
			
			e.preventDefault();
			var obj = $(this);
		
			var nom, cognoms, email, telefon, comment;
			
			var color_er = '#EE281B';
			var color_ok = '#FFCC00';					
			
			nom   = $('#nom').val();
			cognoms   = $('#cognoms').val();
			email = $('#email').val();
			telefon = $('#telefon').val();
			comment    = $('#comment').val();
			promo    = $('#promo').val();
			
			//result = $('#result').val();		
			
			//var form_info = obj.find('.form-info');
			
			if (!nom){
				$('#nom').css("border",'1px solid '+color_er);
				$('#nom').focus();		
				//form_info.html('<?php echo get_nom_error(); ?>');
				
				return false;
			}else
				$('#nom').css("border",'1px solid '+color_ok);
				
			if (!cognoms){
				$('#cognoms').css("border",'1px solid '+color_er);
				$('#cognoms').focus();				
				//form_info.html('<?php echo get_cognoms_error(); ?>');
				
				return false;
			}else
				$('#cognoms').css("border",'1px solid '+color_ok);			
			
			if (!telefon){
				$('#telefon').css("border",'1px solid '+color_er);
				$('#telefon').focus();				
				//form_info.html('<?php echo get_telefon_error(); ?>');
				
				return false;
			}else
				$('#telefon').css("border",'1px solid '+color_ok);
				
			if (!email){
				$('#email').css("border",'1px solid '+color_er);
				$('#email').focus();				
				//form_info.html('<?php echo get_noemail_error(); ?>');
				
				return false;
			}else{
				if (!isEmailAddress(email)){
					$('#email').css("border",'1px solid '+color_er);
					$('#email').focus();					
					//form_info.html('<?php echo get_email_error(); ?>');
					
					return false;
				}else
					$('#email').css("border",'1px solid '+color_ok);				
			}
			
			
				
			if (!comment){
				$('#comment').css("border",'1px solid '+color_er);
				$('#comment').focus();				
				form_info.html('<?php echo get_message_error(); ?>');
				
				return false;
			}else
				$('#comment').css("border",'0px');
			
			if (one_time){
				one_time=false;
				$("#bt_enviar").val("Enviando...");
				var senddata="nom="+nom+"&email="+email+"&cognoms="+cognoms+"&telefon="+telefon+"&comentaris="+comment+"&promo="+promo;
				$.ajax({
					url: absPath+"/email.php",
					cache: false,
					data: senddata,
					success: function(xml){
						if (jQuery(xml).find('error').text()=="0"){
							obj.slideUp();
							$("#formOK").fadeIn("slow");
						} else {
							alert("Error de connexión con el servidor");
						}
						
				},
				error: function(err){
					alert("Error de connexión con el servidor");
				}
				});
				
			}
			
		})
			
	})
	
	function isEmailAddress(email) 
	{
		var s = email;	
		var filter=/^[A-Za-z-_.][A-Za-z0-9_.-]*@[A-Za-z0-9_-]+\.[A-Za-z0-9_.-]+[A-za-z]$/;	
		if (s.length == 0) return false;		
		if (filter.test(s)) return true;
		else return false;
	}
			
	jQuery.fn.reset = function () {
	  $(this).each (function() { this.reset(); });
	}	
	
	
	
	function messageOK() {
		$('#contactform').reset();
		$('#contactform').find('.form-info').html('<?php echo contact_send_ok(); ?>');
	}
	
	function setMSG(MSG){
		$('#contactform').reset();
		$('#contactform').find('.form-info').html(MSG);
	}
	
var moving=false;	
$.fn.slider = function() {

	var $gallery=$(this);
	var $ul=$gallery.children().children("ul");
	var $controls=$gallery.children(".controls");
	var widthLi=$ul.children("li:eq(0)").outerWidth(true);
	var numLi=0;
	var widthW;
	var offset=200; //margen para poner flechas
	var actual=0;
	var it;
	
	numLi=$ul.children().length;
	
	$(window).resize( function() { calculateGallery(); });
	
	// ponemos el width al ul
	$ul.width(widthLi*numLi);
	
	calculateGallery();
	
	$controls.children("div.left,div.right").bind("mouseover mouseout mousedown mouseup touchstart touchend",function(evt){
	
	evt.stopPropagation();
	evt.preventDefault();
		var salto=3;
		
		var leftA={	left: "+="+salto+"px"};
		var leftB={	left: "-="+salto+"px"};
		var rightA = {	right: "+="+salto+"px"};
		var rightB = {	right: "-="+salto+"px"};
		
		if ($(this).hasClass("left")){
			var opA=leftA;
			var opB=leftB;
			var $f=$(".left_img");
			var dir="+";
			
		} else {
			var opA=rightA;
			var opB=rightB;
			var $f=$(".right_img");
			var dir="-";
			
		}
		
		
		if (evt.type=="touchstart"){
				
				smove($ul,dir+"="+widthLi+"px",100);
			
		} else if (evt.type=="mouseup" || evt.type=="touchend"){
			
			
			
			//$f.stop(true,true).animate(opA, 30);
			}
		else if (evt.type=="mousedown"){
			//$f.stop(true,true).animate(opB, 30);
		} else if (evt.type=="mouseover"){
		
			smove($ul,dir+"="+widthLi+"px",400);
			it=setInterval(function(){
				smove($ul,dir+"="+widthLi+"px",400);
			},800);
			$f.stop(true,true).animate(opB, 100);	
		}																
		else if (evt.type=="mouseout"){
			clearInterval(it);
			$f.stop(true,true).animate(opA, 100);
			
		}
		
	})
	
	function smove($ul,l,v){
		if (!moving){
			moving=true;
			$ul.stop(true,true).animate({	left: l}, v,function(){moving=false; show_controls();});
		}
	}
			
	function calculateGallery(){
		
		/*if (window.innerWidth) {
        //navegadores basados en mozilla
        var width = window.innerWidth - offset;
    	} else {
        //Navegadores basados en IExplorer, es que no tengo innerheight
        var width = document.body.clientWidth - offset;
    	}*/
    	
    	var width=$("#header").width()-offset;
    	
    	widthW=widthLi*numLi;
    	
    	controls=false;
    	while (width<widthW){
    		widthW-=widthLi;
    		controls=true;
    	}
    	
    	if (controls)
    		$controls.show();
    	else
    		$controls.hide();
   
   
    	$gallery.width(widthW);
    	
    	
    	// controlamos que no se pase
    	
    	if ($ul.width()<Math.abs($ul.position().left)+widthW){
    		
    		//$ul.css("marginLeft: "+="+widthLi+"px"});
    		$ul.stop(true,true).animate({	left: "+="+widthLi+"px"}, 0);
    	}
    	
    	show_controls();
    	
   }
	
	function show_controls(){
		
		if ($ul.position().left==0){
			$(".left").hide();
			$(".left_img").hide();
			clearInterval(it);
		
		} else {
			$(".left").show();
			$(".left_img").show();
		}
		
		if (Math.abs($ul.position().left)+widthW>=$ul.width()){
			$(".right").hide();
			$(".right_img").hide();
			clearInterval(it);
		} else {
			$(".right").show();
			$(".right_img").show();
		}
		
	}
	
}

function getInternetExplorerVersion()
// Returns the version of Windows Internet Explorer or a -1
// (indicating the use of another browser).
{
   var rv = -1; // Return value assumes failure.
   if (navigator.appName == 'Microsoft Internet Explorer')
   {
      var ua = navigator.userAgent;
      var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
      if (re.exec(ua) != null)
         rv = parseFloat( RegExp.$1 );
   }
   return rv;
}
function checkIEVersion()
{
   var msg = "You're not using Windows Internet Explorer.";
   var ver = getInternetExplorerVersion();
   if ( ver> -1 )
   {
      if ( ver>= 8.0 )
         msg = 8;
      else if ( ver == 7.0 )
    	  msg = 7;
      else if ( ver == 6.0 )
    	  msg = 6;
      else
    	  msg = 0;
    }
   return( msg );
}

