$(document).ready(function() {
	
	// inicializar menu principal
	initMainMenu();

	// Inicializacion de variables y propiedades
	var URLS_local = new Boolean(true);
	var mostrarIntructivo = new Boolean(false);
	
	var URL_proxy_movieData = "xml-proxies/xmlMovies.php";
	var URL_proxy_nextMovieData = "xml-proxies/xmlNextMovies.php";
	
	var URL_topHeader = "js-includes/main-header_localTest.html";
	var URL_bottomHeader = "js-includes/main-footer.html";
	
	if (URLS_local== true){
		URL_XMLScore = "xml-data/XMLdataScore.xml";
		URL_proxy_movieData = "xml-data/movieData.xml";
		URL_proxy_nextMovieData = "xml-data/nextMovieData.xml";
	}
	
	var xml_movies = "";
	var popupStatus = 0;
	var codPelicula = "";
	
	var $dep_wPopup = $("#ytPopup");
	var $dep_bkgPopup = $("#backgroundPopup");
	
	function loadPopup(){  
		//loads popup only if it is disabled  
		if(popupStatus==0){  
			$dep_bkgPopup.css({  
					"opacity": "0.7"  
			});  
			$dep_bkgPopup.fadeIn("slow");  
			$dep_wPopup.fadeIn("slow");  
			popupStatus = 1;  
		};  
	};
	
	function disablePopup(){  
		if(popupStatus==1){ 
			$("#ytObject").remove(); 
			$dep_bkgPopup.fadeOut("slow");  
			$dep_wPopup.fadeOut("slow");  
			popupStatus = 0;  
		};  
	};
	
	function centerPopup(){  
		//request data for centering  
		var windowWidth = document.documentElement.clientWidth;  
		var windowHeight = document.documentElement.clientHeight;  
		var popupHeight = $dep_wPopup.height();  
		var popupWidth = $dep_wPopup.width();  
		//centering  
		$dep_wPopup.css({  
			"position": "absolute",  
			"top": windowHeight/2-popupHeight/2,  
			"left": windowWidth/2-popupWidth/2  
		});  
		//only need force for IE6  
  
		$dep_bkgPopup.css({  
			"height": windowHeight  
		});
	};
	
	$("#popupClose").click(function(){  
		disablePopup();  
	});  
	//Click out event!  
	$dep_bkgPopup.click(function(){  
		disablePopup();  
	});  
	//Press Escape event!  
	$(document).keypress(function(e){  
		if(e.keyCode==27 && popupStatus==1){  
			disablePopup();  
		}; 
	}); 
	
	
	if (nombreSelected == "home"){
		
		$dep_estrenos = $("#h-promo-estrenos");
		$dep_proximos = $("#h-promo-proximos-estrenos");
		
		$.get(URL_proxy_movieData, {}, function(xmlMov){
			
			$dep_estrenos.html("");// limpiado de contenidos
			var htmlStr = "";
			var srcLoc = 'http://www.procinal.com/peliculas-img/';
			var hlink = '<div class="pelicula"><a href="peliculas-en-cartelera.html?idp=';
			
			var id1 = $("pelicula:eq(0)", xmlMov).attr("id");
			var id2 = $("pelicula:eq(1)", xmlMov).attr("id");
			var id3 = $("pelicula:eq(2)", xmlMov).attr("id");
			
			htmlStr += hlink+id1+'"><img src="' + srcLoc + id1 + '.jpg"/></a></div>';
			htmlStr += hlink+id2+'"><img src="' + srcLoc + id2 + '.jpg"/></a></div>';
			htmlStr += hlink+id3+'"><img src="' + srcLoc + id3 + '.jpg"/></a></div>';
			
			$dep_estrenos.html(htmlStr);
				
		}, "xml");
		
		// cargar movieData para mostrar ultimos estrenos
		
		$.get(URL_proxy_nextMovieData, {}, function(xmlNext){
			
			$dep_proximos.html("");// limpiado de contenidos
			var htmlStr = "";
			var bloq1 = '<div class="pelicula"><a href="proximos.html"><img src="http://www.procinal.com/peliculas-img/';
			var bloq2 = '.jpg" width="96" height="150"/></a><span class="h-fecha-estreno">';
			var bloq3 = '</span></div>';
			
			for ( i=0; i<8; i+=1 ){
				var tempSelector = "pelicula:eq("+i+")";
				htmlStr += bloq1 + $(tempSelector, xmlNext).find("data").attr("cartel");
				htmlStr += bloq2 + $(tempSelector, xmlNext).find("data").attr("fechaEstreno") + bloq3;
			}
			
			$dep_proximos.html(htmlStr);
			
		}, "xml");
		
		//startAnimationBannersFLA();
		startAnimationBanners();
		
	};
	
	
	if (nombreSelected == "proximos"){
		
		// establecimiento variables
		var xmlNM = '';
		
		
		//Domain entry points
		var $dep_barraSup = $("#pe-barraSup");
		var $dep_tituloPelicula = $("#pe-titulo-pelicula");
		var $dep_listaPeliculas = $("#pe-list-peliculas ul");
		var $dep_cartel = $("#pe-cartel");
		var $dep_nombrePelicula = $("#pe-titulo-pelicula");
		var $dep_sinopsis = $("#pe-tx-sinopsis");
		var $dep_fichaTecnica = $("#pe-data-ft");
		var $dep_botonTrailer = $("#pe-boton-yt");
		
		// cargar proximos estrenos
		$.get(URL_proxy_nextMovieData, {}, function(xml){inicializarProximos(xml);}, "xml");
		
		
		
		function inicializarProximos(xml){
			
			xmlNM = xml;
			
			// creacion carteles superiores
			$dep_barraSup.html("");// limpiado de contenidos
			var htmlStr = "";
			var bloq1 = '<div class="pelicula"><a href="javascript:;"><img src="http://www.procinal.com/peliculas-img/';
			var bloq2 = '.jpg" width="96" height="150"';
			var bloq3 = '/></a><span class="h-fecha-estreno">';
			var bloq4 = '</span></div>';
			
			for ( i=7; i>=0; i-=1 ){
				var tempSelector = "pelicula:eq("+i+")";
				htmlStr += bloq1 + $(tempSelector, xmlNM).find("data").attr("cartel") + bloq2;
				htmlStr += ' nombrePelicula="'+$(tempSelector, xmlNM).attr("nombre")+'"';
				htmlStr += bloq3 + $(tempSelector, xmlNM).find("data").attr("fechaEstreno") + bloq4;
			};
			$dep_barraSup.html(htmlStr);
			
			// popular lista de peliculas próximas
			$dep_listaPeliculas.html("");// limpiado de contenidos
			var htmlStr = "";
			
			$("pelicula", xmlNM).each(function(){
				var idPelicula = $(this).attr("id");
				htmlStr += '<li><a href="javascript:;">';
				htmlStr += $(this).attr("nombre") + '</a></li>';
			});
			$dep_listaPeliculas.html(htmlStr);
				
			selectedPelicula = $("pelicula:first", xmlNM).attr("nombre");
			get_movie_techData(selectedPelicula);
			marcaPeliculasClick(null);
			marcaPeliculasClick(selectedPelicula);
			
			function marcaPeliculasClick(datos){
				
				if (datos != null){
					//remoción element marcado viejo
					$dep_listaPeliculas.find("li a.rem").removeClass("rem");
					$dep_listaPeliculas.find("li a:contains("+datos+")").addClass("rem");
				}else{
					$dep_listaPeliculas.find("li a").click(function(){
			
						selectedPelicula = $(this).html();
						get_movie_techData(selectedPelicula);
						
						//remoción element marcado viejo
						$dep_listaPeliculas.find("li a.rem").removeClass("rem");
						//marca elemento del listado
						$(this).addClass("rem");
				
					});
				};
			};
			
			function get_movie_techData(nombre){
			
				var tempFichaTech = $("pelicula[nombre="+nombre+"]", xmlNM).find("data");
				var tempPelicula = $("pelicula[nombre="+nombre+"]", xmlNM);
			
				var imgSrc = 'http://www.procinal.com/peliculas-img/'+tempFichaTech.attr("cartel")+'.jpg';
			
				var loadHtmlStr = "";
				loadHtmlStr += '<div id="load-img">';
				loadHtmlStr += '<img src="img_plantillas/_spining_splash.gif"/>';
				loadHtmlStr += '</div>';
				loadHtmlStr += '<div id="load-tx">';
				loadHtmlStr += 'Espere un momento cargando cartel</div>';
			
				$dep_cartel.html(loadHtmlStr);
			
				var noDisponibleHtml = "";
				noDisponibleHtml += '<div id="load-img">';
				noDisponibleHtml += '<img src="img_plantillas/_no_disponible.gif"/>';
				noDisponibleHtml += '</div>';
				noDisponibleHtml += '<div id="load-tx">';
				noDisponibleHtml += 'Cartel no disponible</div>';
			
				//funcion de carga y handlers
				var img = new Image();
				$(img).load(function(){
					$dep_cartel.html("");
					$(this).css('display','none');
					$dep_cartel.append(this);
					$(this).fadeIn();
				}).error(function(){
					$dep_cartel.html(noDisponibleHtml);
				}).attr('src', imgSrc);
				
				
				
				$dep_sinopsis.html(tempPelicula.find("sinopsis").text());
				$dep_sinopsis.jScrollPane();
				$dep_nombrePelicula.html(selectedPelicula);
				
				var htmlStrFT = '';
				var iniHead = '<span class="contenedor-gen-ficha"><span class="subtitulo">';
				var midHead = ':</span><span class="dataFT">';
				var endHead = '</span></span>';
				
				htmlStrFT += '<div id="pe-fecha-estreno">';
				htmlStrFT += '<span class="titulo">Fecha de Estreno: </span>'+tempFichaTech.attr("fechaEstreno")+'</div>';
				
				htmlStrFT += '<div id="pe-contenedor-lineas">';
				
				htmlStrFT += iniHead+'Título Original'+midHead+tempFichaTech.attr("toriginal")+endHead;
				htmlStrFT += iniHead+'Dirección'+midHead+tempFichaTech.attr("director")+endHead;
				htmlStrFT += iniHead+'País'+midHead+tempFichaTech.attr("pais")+endHead;
				htmlStrFT += iniHead+'Idioma'+midHead+tempFichaTech.attr("idioma")+endHead;
				htmlStrFT += iniHead+'Genero'+midHead+tempFichaTech.attr("genero")+endHead;
				htmlStrFT += iniHead+'Censura'+midHead+tempFichaTech.attr("censura")+endHead;
				htmlStrFT += iniHead+'Duración'+midHead+tempFichaTech.attr("duracion")+" minutos"+endHead;
				
				htmlStrFT += '</div>';
				
				htmlStrFT += '<div id="pe-calificacion">';
				htmlStrFT += '<div class="titulo">Calificación:</div>';
				
				/*htmlStrFT += '<div class="js-kit-rating" view="combo" ';
				htmlStrFT += 'uniq="/idmovie'+tempFichaTech.attr("videoYouTube");
				htmlStrFT += '" starColor="Golden" title="'+selectedPelicula+'"></div>';
				htmlStrFT += '<script src="http://js-kit.com/for/procinal.com/ratings.js"></script>';*/
				
				htmlStrFT += '</div>';
				
				// insercion datos en el DOM
				$dep_fichaTecnica.html(htmlStrFT);
				
				
				// trailer de youtube         -------------------------------------------------------------->>
				var traileryt = tempFichaTech.attr("videoYouTube");
				
				$dep_botonTrailer.hover(function() {
					$(this).css("background-image", "url(img-proximos/botonYtHover.jpg)");
  				}, function() {
    				$(this).css("background-image", "url(img-proximos/botonYt.jpg)");
 				});
			
				$dep_botonTrailer.click(function(){
					
					var youYubeHtml = '';
					
					youYubeHtml += '<div id="ytObject">';
					youYubeHtml += '<object width="480" height="310">';
					youYubeHtml += '<param name="movie" value="http://www.youtube.com/v/' + traileryt + '&hl=es&fs=1&rel=0"></param>';
					youYubeHtml += '<param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always">';
					youYubeHtml += '</param><embed src="http://www.youtube.com/v/' + traileryt + '&hl=es&fs=1&rel=0" ';
					youYubeHtml += 'type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" ';
					youYubeHtml += 'width="480" height="310"></embed></object>';
					youYubeHtml += '</div>';
					
					centerPopup();
					loadPopup();
					$dep_wPopup.find("h1").html("Trailer: "+selectedPelicula);
					$("#ytPlayerContent").html(youYubeHtml);
					
				});
			
			};
			
			$dep_barraSup.find("img").click(function(){
				selectedPelicula = $(this).attr("nombrePelicula");
				get_movie_techData(selectedPelicula);
				marcaPeliculasClick(selectedPelicula);
			});
			
		};// fin proximos estrenos
		
	};
	//-------- Fin document.ready		
});


function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}

function startAnimationBanners(){
	
	// animación banners...
	
	
	var intervalo = 8000;
	var tanimacion = 1000;
	var contadorImagenes = 0;
	var imagenes = ['promosN/promoavesnuevassalas2011.jpg', 'promosN/promocrush1000.jpg', 'promosN/dulcinema.jpg'];
	var cantidadImagenes = imagenes.length;
	var htmlt = '';
	
	// precarga de imagenes
	function precargaFondos(){
		window.clearTimeout();
		var imgObj = new Image();
		imgObj.src = imagenes[contadorImagenes];
		if(!imgObj.complete){
			// error de carga;
			// en caso de error por recursividad de elementos en carga vuelva a intentarlo
			window.setTimeout(precargaFondos, 500);
		}else{
			var urli = imagenes[contadorImagenes];
			htmlt += '<div class="banner_item" style="background: black url('+urli+') no-repeat 50% 50%;)"></div>';
			contadorImagenes += 1;
			if (contadorImagenes<cantidadImagenes){
				precargaFondos();
			}else{
				contadorImagenes = 0;
				$('#main_banner_c').html(htmlt);
				htmlt = '';
				animarBg();
			}
		}
		
	}
	
	var actual = contadorImagenes-1;
	var siguiente = 0;
	
	function animarBg(){
		
		if ( actual == -1 && siguiente == 0 ){
			$('#main_banner_c').find('div:eq(0)').fadeIn(tanimacion);
			updatecounter();
		}else if( actual >= 0 && siguiente < cantidadImagenes ){
			$('#main_banner_c').find('div:eq('+actual+')').fadeOut(tanimacion);
			$('#main_banner_c').find('div:eq('+siguiente+')').fadeIn(tanimacion);
			updatecounter();
		}else if(siguiente == cantidadImagenes){
			$('#main_banner_c').find('div:eq('+actual+')').fadeOut(tanimacion);
			$('#main_banner_c').find('div:eq(0)').fadeIn(tanimacion);
			actual = 0;
			siguiente = 1;
		}
		
		function updatecounter(){
			actual += 1;
			siguiente = actual+1;
		}
		
		function maketime(){
			window.setTimeout(animarBg, intervalo);
		}
		
		maketime();
	}
	
	window.setTimeout(precargaFondos, 500);
}

function startAnimationBannersFLA(){
	
	var bannerdep = 'main_banner_c';
	//flashembed(bannerdep, {src: '../assets/ads/banerpitufos.swf', wmode: 'opaque'});
	
}

