// Intro img batch loading plugin
var myBulk=0;
(function($){
	$.fn.loadImage = function(options){
		var defaults = {
			src: "none",
			bulk: 1,
			onLoadFinish: null
		};
		var options = $.extend(defaults, options);
		return this.each(function(){
			var me = this;	
			var img = new Image();
			$(img).attr("src",options.src).load(function(){
				myBulk++;
				if (myBulk == options.bulk) {
					if (options.onLoadFinish) { options.onLoadFinish(me); }
					myBulk = 0;
				}
			
			}).appendTo(this);
		});
	};
})(jQuery);


// Google Books plugin
jQuery.GBSV = {

	url : 'http://books.google.com/books',
	base_query : 'jscmd=viewapi&callback=jQuery.GBSV.processBookInfoResponse&bibkeys=',
	
	init : function(){
		var bibkeys = [];
		var found_elements = this.found_elements={}
		
		jQuery('a.googlebooks').each(function(){
			var t=jQuery(this)
			bibkeys.push(t.attr('rel'));
			found_elements[t.attr('rel')] = found_elements[t.attr('rel')] ? found_elements[t.attr('rel')] : []
			found_elements[t.attr('rel')].push(t);
		});
		//console.log(bibkeys.length);
		/*
		// TODO batch requests
		var bibkeysLength = bibkeys.length;
		if (bibkeysLength > 20) {
			var loops = Math.ceil(bibkeysLength/20);
			for(var i==0; i==loops; i++){
				var batchArray = [];
				if(i==0){
					batchArray[i][];
					batchArray[i] = bibkeys.slice(X,X);
				} else {
					batchArray[i] = bibkeys.slice(X,X);
				}
			}
		} else {
			this.loadFromBibKeys(bibkeys);
		}
		*/
		this.loadFromBibKeys(bibkeys);
	},
	
	loadFromBibKeys : function(bibkeys){
		jQuery('body').append('<script src=' + this.createRequestURL(bibkeys) + '/>');
	},
	
	createRequestURL : function(bibkeys){
		return this.url + '?' + this.base_query + this.arrayUnique(bibkeys).join(',')
	},
	
	arrayUnique : function(src_array){
		var o = new Object();
		var i, e;
		for (i = 0; e = src_array[i]; i++) {o[e] = 1};
		var a = new Array();
		for (e in o) {a.push (e)};
		return a;
	},
	
	processBookInfoResponse : function(data){
		
		for(bibkey in this.found_elements){
			for(i in this.found_elements[bibkey]){
				//console.log(data['preview']);
				this.processElement(this.found_elements[bibkey][i], data[bibkey]);
			}
		}
	},
	
	processElement : function(el, data){
		if(el[0].tagName=='A'){
			var viewableStatus = data['preview'];
			if (viewableStatus == "partial" || viewableStatus == "full" ) {
				el.addClass("showlink");
			}
		}
	}
}

jQuery(function(){
	
	$("#wrapper").addClass("jsactive");
	
	var langAvail = ["fr","es","en","pt"];
	var langSelect = 0;
	for (var i=0; i<=3;i++) {
		if($("body").hasClass(langAvail[i])) { langSelect = i; }
	}
	var locationHref = location.href;
	
	// ! INTRO
	function randOrd(){	return (Math.round(Math.random())-0.5); }
	
	var introImages = [0,1,2,3,4,5,6,7,8,9,10];
	introImages.sort(randOrd);
	
	var introSwitchFoto = function() {
		var $active = $('#gallery img.active');
	    if ( $active.length === 0 )  { $active = $('#gallery img:first'); }
	    var $next =  $active.next().length ? $active.next() : $('#gallery img:first');	
	    $active.addClass('last-active');
	    $next.css({ opacity: 0 }).addClass('active').animate({ opacity: 1 }, 1000, function() { 
	    	$active.removeClass('active last-active'); 
	    });	
	};
	
	var startIntervallOnlyOnce = true;
	var startIntervall = function() { intervalID = window.setInterval(introSwitchFoto, 2500);	};
	var loadFotoBulk = function() {
		var imagepath = "/fileadmin/sys/gfx/intro/";
		for(var i=1; i < introImages.length; i++) {
			var src = imagepath+"fot_"+introImages[i]+".jpg";
			$("#gallery").loadImage({
				 src: src,
				 onLoadFinish : function() {
				 	if (startIntervallOnlyOnce) {
				 		//startIntervall();
				 		//introSwitchFoto();
				 		startIntervallOnlyOnce = false;
				 	}
				 }
			 });
		}
	};
	
	var loadFirstImage = function(i){
		var me = this;	
		var img = new Image();
		$(img).attr("src","/fileadmin/sys/gfx/intro/fot_"+i+".jpg").load(function() { 
			loadFotoBulk(); 
			startIntervall();
		}).appendTo("#gallery");
		$('#gallery img').addClass("active");
	};
	
	loadFirstImage(introImages[0]);
	
	// ! RESIZE Intro
	function initWindowSize() {
			var windowHeight = $(window).height();
			if (windowHeight < 800) {
				$(".intro #wrapper").css("margin-top", 65);
			} else {
				$(".intro #wrapper").css("margin-top", 150);
			}
	}
	$(window).resize(function(){ initWindowSize(); });
	initWindowSize();
	
	// ! #pagelabel correction, no effect on display-cell declarations!!!
	var $pageLabel = $("#pagelabel span");
	if($pageLabel.height() > 15) {
		var h = $pageLabel.height();
		$pageLabel.css("margin-top","-"+h/2+"px");
		
	}
	
	// ! NAVI
	var $navLevel_1 = $("#center .navi ul").not(".public #center .navi ul, #center .navi ul ul ul").prev("a");
	var $navLevel_2 = $("#center .navi ul ul ul").prev("a");

	$navLevel_1
	.click(function() {
		var $parent = $(this).parent()
		// Open if closed
		if( !$parent.hasClass("hover") && !$parent.hasClass("current-parent") ) {
			//var thisURL = $(this).attr("href");
			var toHeight = 0;

			var thisParentHeight = $parent.height();
			$parent
			.height(thisParentHeight)
			.addClass("hover")
			.children("ul").children("li")
			.each(function(){
			  var thisHeight = $(this).height();
			  $(this).height(thisHeight).css("opacity",0).animate({ opacity:1 }, 800);
			  // +1 for borders
			  toHeight += Number($(this).height())+1;
			});
			// set aim size and correct because of -1px margin
			toHeight += thisParentHeight-1;
			$parent.animate({height: toHeight },500, function() { $(this).css("height","auto"); } );

		} else {
			$parent.height("").removeClass("hover");
		}
				
		return false;
	});

	$navLevel_2
	.click(function() {

		var toHeight = 0;
		var $parent = $(this).parent()
		// if not .entry-level-0 this points to Sub-site
		if ($parent.hasClass("entry-level-0")) {
			var thisParentHeight = $(this).parent().height();
			
			if(!$parent.hasClass("hover") && !$parent.hasClass("current-parent") ){
				
				$parent
				.height(thisParentHeight)
				.addClass("hover")
				.children("ul").children("li")
				.each(function(){
				  var thisHeight = $(this).height();
				  $(this).height(thisHeight).css("opacity",0).animate({ opacity:1 }, 800);
				  // +1 for borders
				  toHeight += Number($(this).height())+1;
				});
				// set aim size and correct because of -1px margin
				toHeight += thisParentHeight-1;
				
				$parent.animate({height: toHeight },500, function() { $(this).css("height","auto"); });
			
			}
			
			//$("#content").load(thisURL+" #content .left" )		
			return false;
		}
	});
	



	$("#center .navi li").not("#center .navi li li").mouseleave(function() {
	  	//$("#center .navi li").removeClass("hover");
	});

	// ! HISTOIRE FOTOS
	$(".histoire #content .right a").click(function(){
		var thisLink = $(this);
		var imgHref = $(this).attr("href");
		var description = $(this).children("img").attr("alt");
		var actualImg = $("#content .left img");

		var img = new Image();
		$(img).load(function() {
			//thisLink.toggleClass("test");
			var imgContainer = $("#content .left .csc-textpic-image dt");
			imgContainer.height(imgContainer.height());
			imgContainer.css({ overflow: "hidden", backgroundColor: "#fff"});
			
			$(this).appendTo("#content .left .csc-textpic-image dt");
			var newImgHeight = $(this).height();
			var newImgWidth = $(this).width();
			
			imgContainer.height(newImgHeight+2).width(newImgWidth+2);
			$(this).css("opacity",0).animate({opacity:1}, 1000, function() {
				$("#content .left .csc-textpic-caption p").html(description);
			});			
			actualImg.remove();
			imgContainer.css("height","auto");
		});
		
		$(img).attr("src",imgHref);
				
		return false;
	});
	
	// ! SEARCH
	$(".left .tx-indexedsearch-form input").focus();
	
	// ! FORMS
	$("#content .left .powermail_select, .left select").not(".shop-advancesearch-block select, #cart_select, #newsletter_country_select").sSelect();
	// Select of category and years in advance search
	$(".shop-advancesearch-block #shop_book_category, .shop-advancesearch-block #shop_book_collection").sSelect();
	$(".shop-advancesearch-block #shop_book_date_from, .shop-advancesearch-block #shop_book_date_to").sSelect({ddMaxHeight: '80px'});
	// Cart
	$("#cart_select").sSelect().change(function(){ $('#cart-form').submit(); return false;});

	// ! Newsletter & Contact from
	$("#newsletter_country_select").sSelect({ddMaxHeight: '150px'});	
	$('#content .left input[type=checkbox], #content .left input[type=radio]').checkbox({
		empty: '/fileadmin/sys/js/img/empty.png'
	});


	// ! NEWS future Events
	var futureEventsText = ["Montrer les événements à venir","Mostrar futuros eventos","Show future events","Mostrar futuros eventos"];
	var futureEventsTextActive = ["Événements à venir","Futuros eventos","Future events","Futuros eventos"];
	var locationHrefAnchor_arr = locationHref.split("#");
	
	// ! FUTURE EVENTS - Hide future Events
	var hiddenImgSrc = [];
	if (locationHrefAnchor_arr[1] != "futureEvents") {
		$("#content .limit")
		.each(function(i) {
			$(this).css("display","none");
			var $thisImg = $(this).find("img");
			if($thisImg.length !== 0) {
				var imgSrc = $thisImg.attr("src");
				hiddenImgSrc[i] = imgSrc;
				$thisImg.attr("src","");
			}
			
		})
		.eq(0)
		.before("<ul class='browsebox' id='futureEvents'><li><a href='"+locationHref+"#futureEvents'>"+futureEventsText[langSelect]+"</a></li></ul>");
		
		// !Show future events
		$("#futureEvents").click(function() {
			$(this).hide();
			$(this).before("<h1 id='futureEvents'><br/>"+futureEventsTextActive[langSelect]+"</h1>");
			$("#content .limit").each(function(i) {
				var $thisImg = $(this).find("img");
				// only activate images if there are any
				if($thisImg.length !== 0) {
					$thisImg.attr("src", hiddenImgSrc[i]);
				}
				$(this).css("display","block");
			});
			window.location.href = locationHref+"#futureEvents";
		});	
	} else {
		$("#content .limit").eq(0).before("<h1 id='futureEvents'><br/>"+futureEventsTextActive[langSelect]+"</h1>");
		window.location.href = locationHref;
	}
	
	// !Google Books preview check
	//$.GBSV.init();
	
});

