/*
*	Version 1.2
*/


jQuery(function(){
	//DEBUG = true;
	//$.log("");
	//$("").log();
	var body = $("body");
	// ! language specific js-strings for future use
	var languages = ["es","gl","ca","eu","en"];
	var descarga_arr = ["Descargar imagen","Descargar","Descargar","Descargar","Download"];
	var vervideo_arr = ["Ver video","Ver video","Ver video","Ver video","Ver video"];
	var cerrarflash_arr = ["Cerrar","Cerrar","Cerrar","Cerrar","Close"];
	var langID = 0;
	var bodyLang = body.attr("class");
	// set id for document language
	for(var i=0; i< languages.length; i++) {
		if (languages[i] == bodyLang) {
			langID = i;
		}
	};
	//$.log(langID);
	// ! Navigation left: specific class for each level

	// Adds .jsactive to all divs with an id
	var navL = $("div[id]");
	navL.addClass("jsactive");
	var navL_li= $("#nav-left li");
	navL_li.addClass("navL-01");
	var navL_li_ul_li= $("#nav-left li ul li");
	navL_li_ul_li.removeClass("navL-01").addClass("navL-02");
	
	// give first level extra class if it has a second level
	var navL_li_ul= $("#nav-left li ul");
	var lev01_a_with_lev02 = navL_li_ul.prev();
	lev01_a_with_lev02.addClass("hasChildren");
	var lev01_hasChild = $(".hasChildren");

	// open first level
	lev01_hasChild.bind("click", function(){
		var this_a_parent = $(this).parent();
		this_a_parent.css("height","auto").addClass("current-active");
		// IE: setting height:auto is not enough, so we force height in px.
		this_a_parent.css("height",this_a_parent.height()+"px");
		
		$(this).css("padding-top","0px");
		// Don't follow links with second level
		$(this).blur();
		return false;
	});
	
	var lev01_li = $(".navL-01");
	var lev02_li = $(".navL-02");

	// hover first level
	lev01_li.bind("mouseenter",	function(){
		// only animate if is not active
		if (!$(this).hasClass("current-active") && !$(this).hasClass("current-item") && !$(this).hasClass("autoheight") /* &&!$(this).hasClass("museovirtual")*/) {
			$(this).children("a").animate({ paddingTop: 3 }, 200);
		}
	});
	
	lev01_li.bind("mouseleave",	function(){	
			$(this).children("a").animate({ paddingTop: 0 }, 200);
			// $.log("out!");
			
			if ($(this).hasClass("current-active")) {
				if (!$(this).hasClass("twolines")) {
					$(this).animate({ height:14 }, 1000 );
				} else {
					$(this).animate({ height:28 }, 1000 );
				}
				$(this).removeClass("current-active");			
			}
			

		}
	);

	// replace word spelling in menu: u to v
	$("#nav-left li a").each( function(){
			var htmlOutput = $(this).html();
			//$.log(htmlOutput);
			if (htmlOutput == "Museo") { $(this).html("Mvseo"); }
			if (htmlOutput == "Patrimonio Subacuático") { $(this).html("Patrimonio Svbacuático"); }
			if (htmlOutput == "Museo Virtual") { $(this).html("Mvseo Virtual"); }
		}
	);


	// ! Navigation center: specific class for each level

	// Preprocess third level: add extra list item with a dot
	$("#nav-content li").before("<li class='dot'>.</li>");
	$("#nav-content li").eq(0).remove();
	
	var navC_ul = $("#nav-content ul");
	var navC_li = $("#nav-content li");
	//navC_ul.addClass("jsactive");
	navC_li.addClass("navC-03");
	
	var navC_li_ul_li= $("#nav-content li ul li");
	navC_li_ul_li.removeClass("navC-03").addClass("navC-04");
	
	// give third level extra class if it has a fourth level
	var navC_li_ul= $("#nav-content li ul");
	var lev03_a_with_lev04 = navC_li_ul.prev();
	var lev03_hasChild_li = lev03_a_with_lev04.parent();
	lev03_a_with_lev04.addClass("hasChildren");
	var lev03_hasChild = $(".hasChildren");

	// hover third level
	var navC_li_widths = [];
	var navC_li_ul_pos = [0];
	var dot_width = $("li.navC-03.dot").width();
	var navC_li_ul_marginLeft = 4;
	$(".navC-03").not(".dot").each(
		function(i) {
			navC_li_widths.push($(this).width());
			if (i>=1) {
				navC_li_ul_pos.push(navC_li_widths[i-1]+navC_li_ul_pos[i-1]+dot_width);
			}
		}
	);
	//$.log(navC_li_widths);
	//$.log(navC_li_ul_pos);
	lev03_hasChild_li.hover(
		function() {
			var thisChildren_ul = $(this).children("ul");
			var index = $(".navC-03").not(".dot").index(this);
			
			var childrenWidth = thisChildren_ul.width();
			var new_ul_left = navC_li_ul_pos[index]+navC_li_ul_marginLeft;
			thisChildren_ul.css("left",new_ul_left);
			
			// Check if last Item gets out of content an corrects position to the left
			var childrenLeft = Number(thisChildren_ul.css("left").slice(0,-2));
			var checksum = childrenLeft+childrenWidth;
			if (checksum >= $("#content").width()) {
				var correctPosition = checksum - $("#content").width()
				thisChildren_ul.css("left",new_ul_left-correctPosition-6);
			}
			
			thisChildren_ul.css("display","block");
			$(this).children("a").addClass("current-active");
		},
		function() {
			$(this).children("ul").css("display","none");
			$(this).children("a").removeClass("current-active");
		}
	);

	
	// ! Search box
	var search_label = $("#search label");
	var search_input = $("#search #queryString");
	search_input.addClass("jsactive");
	
	search_label.click( function() { search_input.removeClass("jsactive"); });
	search_input.blur( function() { search_input.addClass("jsactive"); });
	

	// ! for image preview in Developement
	var content_img = $("#content img");
	var baseUrl = $("base").attr("href");
	var developURL = "http://rucio.mcu.es/iw-mount/default/main/nwMCU/maqueta/web_museos/museoArqua/WORKAREA/museoArqua/museoArqua_public/";
	var locationHref = location.href;
	var seachString = locationHref.search(/rucio.mcu.es/);

	if (seachString != -1) { 
		$("base").remove();
	
		content_img.each( function() {
			var imgSrc = $(this).attr("src");
			var newImgScr = developURL+imgSrc;
			$(this).attr("src",newImgScr);
		});
	}
	
	// ! Download link on any img in content
	var content_a_img = $("#content .noticias a img");	
	content_a_img.each( function() {
		
		$(this).parent().before("<div class='download'><a href=''>"+descarga_arr[langID]+"</a></div>");
		var download_div = $(this).parent().siblings("div.download");
		var downloadWidth = download_div.width();
		
		var imgWidth = $(this).width();
		var imgHeight = $(this).height();
		var a_img_href = $(this).parent().attr("href");

		download_div.children().attr("href",a_img_href);		
		download_div.css({
			marginLeft:(imgWidth/2)-(downloadWidth/2),
			marginTop: (imgHeight/2)-9,
			position: "relative"
		});
		
	});
	content_a_img.bind("mouseenter", function() {
		var download_div = $(this).parent().siblings("div.download");
		download_div.css("display","block");
	});
	content_a_img.bind("mouseleave", function() {
		var download_div = $(this).parent().siblings("div.download");
		download_div.css("display","none");
	});
	
	function fotonavigation(p) {
		
		var thisGallery = p;
		var thisGallery_scroll = thisGallery.children(".scroll-container");
		var thisGallery_ul = thisGallery.find("ul");
		var thisGallery_li = thisGallery.find("li");
		var thisGallery_img = thisGallery.find("img");
		var thisGallery_a = thisGallery.find("a");
		thisGallery_scroll.css("overflow","hidden");
		// Predifine total width for later enabling left floating images
		var ul_totalWidth = 0;
		// Predefine Arrays
		var img_widths = [];
		img_widths[0] = 0;
		var scrollTo = [];
		scrollTo[0] = 0;
		// for later use need for current img
		thisGallery_img.eq(0).addClass("current");
		// Create image navi only if there ist more than one image
		if (thisGallery_img.length > 1) {
			thisGallery_scroll.before("<div class='js-navigation'></div>");
		}
		var jsNavigation = thisGallery.children(".js-navigation");
		thisGallery_img.each(
			function(i) {
				ul_totalWidth += $(this).width();
				img_widths[i] = $(this).width();
				scrollTo[i+1] = $(this).width()+scrollTo[i];
				//
				if (i == 0) {
					jsNavigation.append("<span class='active'>"+(i+1)+"</span>");
					thisGallery_scroll.css("width", img_widths[0]);
					
				} else {
					jsNavigation.append(".<span>"+(i+1)+"</span>");
				}
		});
		
		thisGallery_ul.css("width",ul_totalWidth+"px");
		
		// ! -- Numbered navigation
		var jsNavigation_span = jsNavigation.children(".js-navigation span");
		jsNavigation_span.hover(
			function() {
				$(this).addClass("hover");
			},
			function() {
				$(this).removeClass("hover");
			}	
		);
		jsNavigation_span.click( function() {
			var index = jsNavigation_span.index(this);
			jsNavigation_span.removeClass("active");
			$(this).addClass("active");
			//$.log(index);
			// Animate scroll content
			thisGallery_ul.animate({marginLeft: -scrollTo[index] }, 1100,"easeInOutCubic");
			// Animate content mask
			thisGallery_scroll.animate({width: img_widths[index] }, 100);
			// Set current image
			thisGallery_img.removeClass("current");
			thisGallery_img.eq(index).addClass("current");
			// For displayed videos
			thisGallery_a.children("object").remove();
			thisGallery_img.css("display","block");
			thisGallery.height(250);
			thisGallery_scroll.height(250);
		});
		
		// ! -- Create download label
		if (thisGallery_a.length > 0) {
			thisGallery_scroll.prepend("<div class='download'><a href=''>"+descarga_arr[langID]+"</a></div>");
			thisGallery_scroll.prepend("<div class='showMovieWrapper'><div class='showmovie'><a href=''>"+vervideo_arr[langID]+"</a></div></div>");
		}
		
		var download_div = thisGallery.find("div.download");
		var showMovie_div = thisGallery.find("div.showmovie");
		var showMovieWrapper_div = thisGallery.find("div.showMovieWrapper");
		
		function loadQuicktime(link,width) {
			var objectString_open = "<object CLASSID='clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B' width='"+width+"' height='256' CODEBASE='http://www.apple.com/qtactivex/qtplugin.cab'>";
			var paramString_1 = "<param name='src' value='"+link+"'>";
			var paramString_2 = "<param name='qtsrc' value='rtsp://realmedia.uic.edu/itl/ecampb5/demo_broad.mov'>";
			var paramString_3 = "<param name='autoplay' value='true'>";
			var paramString_4 = "<param name='loop' value='false'>";
			var paramString_5 = "<param name='controller' value='true'>";
			var embedString = "<embed src='"+link+"' width='"+width+"' height='250' autoplay='true' controller='true'></embed>";
			var objectString_close = "</object>";
			
			var wholeString = objectString_open+paramString_1+paramString_2+paramString_3+paramString_4+paramString_5+embedString+objectString_close;
			
			return wholeString;
			
		}
		var savedLink;
		thisGallery_a.bind( "mouseenter", function() {
				//$.log($(this).attr("href"));
				
				var thisHref = $(this).attr("href");
				savedLink = thisHref;
				var seachStringMov = thisHref.search(/.mov/);
				var actualMaskWidth = thisGallery_scroll.width();
				var downloadWidth = download_div.width();
				var showMovieWidth = showMovie_div.width();
				//
				//$.log(seachStringMov);
				if (seachStringMov == -1) {
					download_div.children().attr("href",thisHref);
					download_div.css({
						left:(actualMaskWidth/2)-(downloadWidth/2),
						top: 120,
						display: "block"
					});
				} else {
					showMovie_div.children().attr("href","#"+thisHref);
					//$(this).attr("href","#"+thisHref);
					showMovieWrapper_div.width(actualMaskWidth);
					showMovieWrapper_div.css("display","block");
					showMovie_div.css({
						left:(actualMaskWidth/2)-(showMovieWidth/2),
						top: 120,
						display: "block"
					});
				}
					
		});
		thisGallery_scroll.bind( "mouseleave", function() {
				showMovieWrapper_div.css("display","none");
				download_div.css("display", "none");
				showMovie_div.css("display", "none");
		});
		showMovieWrapper_div.click( function() {
				var currentImg = thisGallery_img.filter(".current");
				currentImg.css("display","none");
				
				var thisHref = currentImg.parents().attr("href");
				
				var imgWidth = showMovieWrapper_div.width();
				
				//currentImg.parents().append(loadQuicktime(thisHref,imgWidth));
				thisGallery.height(266);
				thisGallery_scroll.height(266);
				
				//return false;
		})
	};


	var fotoGallery = $(".fotogallery");

	// ! Init fotogalleries	
	fotoGallery.each( 
		function() {
			var domreadyInit = true;
			var thisFotonavigation = $(this);
			// ! -- Check if all images of this fotogalery has a width declaration
			$(this).find("img").each(function() {
				$(this).removeAttr("alt");
				var imageWidth = $(this).attr("width");
				//$.log(imageWidth);
				// why is the image width 34 ?!?
				if (imageWidth == 0) {
					domreadyInit = false;
				}
			});
			
			//$.log("init on domready: "+domreadyInit);
			// ! -- if width of one image is not defined, wait until window loads to init the corresponding fotoGallery
			if (domreadyInit) {
				//$.log("dom ready loading");
				fotonavigation(thisFotonavigation);
			} else {
				thisFotonavigation.css("visibility","hidden");
				$(window).load(function() {
					//$.log("window ready loading");
					fotonavigation(thisFotonavigation);
					thisFotonavigation.css("visibility","visible");
				});
			}
			
			var index = fotoGallery.index(this);
			// ! -- if more than one fotogallery reduce margin-bottom of first one
			if (index > 0) {
				fotoGallery.eq(0).css("margin-bottom","14px");
			}
			
		}
	
	);
	
	// ! Sliding gallery for Galeria de Piezas
	function exposition(p) {
		$(document).pngFix(); 
		var thisGallery = p;
		var thisGallery_scroll = thisGallery.children(".scroll-container");
		var thisGallery_ul = thisGallery.children().children("ul");
		
		var thisGallery_li = thisGallery.children().children().children("li");
		var thisGallery_li_current_item = thisGallery.children().children().children("li.current-item");
		var thisGallery_img = thisGallery.children().children().children().children("img");

		// ! -- Predifine total width for later enabling left floating images
		var uls_totalWidth = 0;
		// Predefine Arrays
		var img_widths = [];
		img_widths[0] = 0;
		var scrollTo = [];
		scrollTo[0] = 0;
		// 
		thisGallery_scroll.before("<div class='js-navigation'></div>");
		var jsNavigation = thisGallery.children(".js-navigation");
		var extraWidth = 20;
		thisGallery_ul.each(
			function(i) {
				uls_totalWidth += $(this).width()+extraWidth;
				scrollTo[i+1] = $(this).width()+scrollTo[i];
				//
				if (i == 0) {
					jsNavigation.append("<span class='active'>"+(i+1)+"</span>");
					thisGallery_scroll.css("width", uls_totalWidth[0]);
					
				} else {
					jsNavigation.append(".<span>"+(i+1)+"</span>");
				}
		});
		thisGallery_scroll.css("width",uls_totalWidth+"px");
		//$.log(thisGallery_scroll.width());
		//$.log(scrollTo);

		// ! -- Numbered navigation
		var jsNavigation_span = jsNavigation.children(".js-navigation span");
		jsNavigation_span.hover(
			function() {
				$(this).addClass("hover");
			},
			function() {
				$(this).removeClass("hover");
			}	
		);
		jsNavigation_span.click( function() {
			var index = jsNavigation_span.index(this);
			jsNavigation_span.removeClass("active");
			$(this).addClass("active");
			// $.log(index);
			// Animate scroll content
			thisGallery_scroll.animate({marginLeft: -scrollTo[index] }, 1100,"easeInOutCubic");

		});
		
		
		// Set current ul and start position
		thisGallery_li_current_item.parent().addClass("current-item");
		thisGallery_ul.each( function (i) {
			if ($(this).hasClass("current-item")) {
				thisGallery_scroll.css("margin-left",-scrollTo[i]);
				jsNavigation_span.removeClass("active");
				jsNavigation_span.eq(i).addClass("active");
			}
		})
		
	};
	
	var galleryExposition = $("#exposition");
	galleryExposition.each( function() { exposition($(this)) });
	

	// ! Page specific scripts
	var homePostEntryA = $("#home .post-entry a");
	homePostEntryA.hover(
		function() {
			var thisParentDiv = $(this).parent().parent();
				thisParentDiv.addClass("hover");
			}, 
		function() {
			var thisParentDiv = $(this).parent().parent();
				thisParentDiv.removeClass("hover");
		})
	

	 // ! Cookie managed font sizes
	 var cookieValue = $.cookie('museoArqua_Fonts');
	 
	 if (cookieValue == undefined ) {
	  cookieValue = $.cookie('museoArqua_Fonts','fontsize_normal');
	 }
	 if (cookieValue == "fontsize_normal" ) {
	 	body.removeClass("fontsize_normal");
	 }
	 if (cookieValue == "fontsize_large" ) {
	 	body.addClass("fontsize_large");
	 }
	 
	 var fontSizeNomal = $(".font-size-normal");
	 var fontSizeLarge = $(".font-size-large");
	 
	 fontSizeNomal.click( function() {
	 	body.removeClass("fontsize_large");
	 	 $.cookie('museoArqua_Fonts', 'fontsize_normal');
	 });
	 fontSizeLarge.click( function() {
	 	body.addClass("fontsize_large");
	 	 $.cookie('museoArqua_Fonts', 'fontsize_large');
	 	 
	 });
	 
	
	 // ! Layout corrections
	 var navContent = $("#nav-content ul");
	 if (navContent.length > 0) {
	 	$("#content .post").addClass("fotogaleria");
	 }
	 // if post-related is higher as post-entry correct height visual division
	 $(window).load(function() {
		 var postEntryHeight = $(".post-entry").height();
		 var postRelatedHeight = $(".post-related").height();
		 if (postEntryHeight < postRelatedHeight) {
		 	$(".post-entry").height(postRelatedHeight);
		 }
	});
	 
	 // ! Flash lightbox: <a class="flash" href="/uploads/main.swf?var=juego1">Juego1</a>
	 // See http://www.actionscript.org/forums/showthread.php3?t=130621
	 var flashlightboxDiv = "<div id='flashlightbox'><div id='flashcontainer'></div></div>";
	 $("#content a.flash").attr("onclick","return false;").click(function() {
	 	$("#flashlightbox").remove();
	 	body.prepend(flashlightboxDiv);
	 	var flashlightbox = $("#flashlightbox");
	 	var flashcontainer = $("#flashcontainer");
	 	flashcontainer.css({
	 		height: flashlightbox.height()-40,
	 		width: flashlightbox.width()-40
	 	});
	 	
	 	var flashURL = $(this).attr("href");
	 	$("#flashcontainer").flash({ 
	 		src: flashURL,
	 		width: '100%',
	 		height: '100%'
	 		});
	 	return false;
	 	
	 });
	 // Event delegation for added element
	$('body').click(function(event) {
		var $tgt = $(event.target);
		if ($tgt.is('#flashlightbox')) {
			$tgt.remove();
		}
	});

	 
	//$.log(baseUrl);
	//$.log(cookieValue);
});