var mousemove_timeout =  null;
var detailLoaded = false;

$(document).ready(function() {
	
	window.clearTimeout(mousemove_timeout);
	var showScrollbar = true;
	
	switch (catId)
	{
		case 0:  //home
		case 1:  //home
			homeInit();
			showScrollbar = false;
			break;
		case 2:   //detail
		case 21:  //publication detail
		case 22:  //press detail
		case 23:  //tv detail image
		case 61:  //info/studio detail
		case 75:  //news detail image
		case 85:  //shop detail
		case 94:  //favorites detail
			detailInit();
			showScrollbar = false;
			carouselInit();
			break;
		case 5:  //timeline
		case 7:  //themes
		case 9:  //filters
		case 15:  //movies	
		case 80:  //art shop
		case 81:  //art shop
			listingInit();
			break;
		case 21:  //publication detail
			showScrollbar = false;
			break;
		case 50:  //login
		case 55:  //contact
			break;
		case 70:  //news
		case 71:  //news
		case 82:  //artshop news
			newsInit();
			break;
		case 74:  //news detail
			newsDetailInit();
			//carouselInit();
			break;
		case 90:  //my-favorites
			favoritesInit();
			break;
		default:
			break;
	}
	
	//fadein listings
	$("#listing .img").each(function(index) {
   		$(this).hide().delay(100*index).fadeIn(300);
	});

	
	//twit
	$('a.twitter').click(function(e) {
		//Cancel the link behavior
		e.preventDefault();
		shareIt(10, "-","-");
		return false;
	});
	//fb
	$('a.facebook').click(function(e) {
		//Cancel the link behavior
		e.preventDefault();
		shareIt(20, "-","-");
		return false;
	});
	$('a.facebook2').click(function(e) {
		//Cancel the link behavior
		e.preventDefault();
		shareIt(20, "My favorite Marc Lagrange Photos", "http://lagrange.8bahn.be/" + $(this).attr("href"));
		return false;
	});
	
	//search
	jQuery.fn.inputtoggle = function(){
	  $(this).each(function(index){ 
	    var myvalue = $(this).attr("value");
		$(this).data('def', myvalue);
	    $(this).focusin(function(){
	      if($(this).val() == myvalue)
	      $(this).val("");
	    });  
	    $(this).focusout(function(){
	      if($(this).val() === "")
	      $(this).val(myvalue);
	    });
	  });    
	};
	$('#search label').click(function(e){
		if($('#searchfor').val() != "" && $('#searchfor').val() != $('#searchfor').data('def')) $('#search').submit();
	});
	$("#searchfor").inputtoggle();
	
	//tooltips
	simple_tooltip("#listing a","tooltip");
	
});


function homeInit(){
	
	$('.block').children('img').each(function(index, element) {
		$(this).width("100%");
		$(this).height("100%");
	});
	
	//animation
	$('.block').mouseenter(function(e) {
		  //$(this).children('a').children('img').animate({ height: '110%', left: '-10px', top: '-10px', width: $newW}, 100);*/
         $(this).children('a').children('img').animate({ 
		 	width:  $(this).data('width')*1.1, 
			height: $(this).data('height')*1.1, 
			left:   $(this).data('left'), 
			top:    $(this).data('top')
		}, 100, 'linear');
     }).mouseleave(function(e) {
          //$(this).children('a').children('img').animate({ height: '100%', left: '0', top: '0', width: '100%'}, 200, 'linear');
		  $(this).children('a').children('img').animate({ 
		  	width:  $(this).data('width'), 
			height: $(this).data('height'), 
			left:   '0', 
			top:    '0'
		  }, 100, 'linear');
     });
	
	 $("#projects").masonry({
		itemSelector: '.block',
		columnWidth: 30,
		isAnimated: false
	 });
	 
	 //we can click on the whole info block
	 $('.infoBlock').click(function(e) {
		var url = $(this).find("a").attr('href');
		if(url==null) return;
		window.location = url;
		e.preventDefault();
	 });
	 
	
	 styleSwitcherInit();
	 
	 homeTxtBlocks();
	 
 	//tooltips
	simple_tooltip("#projects a","tooltip");
}

function homeTxtBlocks(){
	
	 //make the text fit
	 $( '.infoBlock' ).each(function ( i, box ) {
		 
		var width = $( box ).width();
		var height = $( box ).height();
		var n = 25;
			
		//to measure place in a hidden layer		
		var resizer = $('<span />', {id: 'hidden-resizer', height: height}).hide().appendTo('body');
		//var resizer = $('<span />', {id: 'hidden-resizer', height: height}).prependTo('body');
		resizer.html( $(box).find("h2 a").html().replace(/ /g, "<br />") );
		resizer.css( 'font-size', n );
		
		while (n>9 && resizer.width() > width ) {
			resizer.css( 'font-size', --n );
		}
		
		//now do the same for the height
		resizer.width(width);
		resizer.height("auto");
		while (n>9 && resizer.height() > height ) {
			resizer.css( 'font-size', --n );
		}
		
		$( box ).css( 'font-size', n );
		
		resizer.remove();
	});
}

function detailInit(){
	
	if($("#detailImg").length < 1) return;
	
	detailLoaded = false;
	$("#detailImg").hide();
	
	$("#detailImg").load(function() {
		placeDetail();
	});
	//images loaded for chrome
	$(window).load(function() {
		placeDetail();
	});
	placeDetail();
	
	//show overlayer + cursor
	window.clearTimeout(mousemove_timeout);
	$('body').mousemove(function(e) {
		if (mousemove_timeout == null) mousemove_timeout = window.setTimeout(function(){detailMousePage(e)}, 150);
	});
	//$("body").trigger({type:"mousemove"});
	
	
	$('body').click(function(e) {
		detailClickPage(e);
	});
	
	//resizing
	$(window).bind("resize", function(){
		resizeDetail();
    });
	resizeDetail();
	
	//align text to the bottom
	$('#overLayer .info').css('top', 150 - $('#overLayer .info').height());

	//styleswitcher get cookie
	if($.cookies.get('browserColor') == 'black') $.stylesheets.clear().add("css/alternative.css");
}
function videoReady() {	
	$('#loading').remove();
}

function detailClickPage(e){
	
	var relativeY = $(window).height() - e.pageY;
	
	//we don't want the bottom of the page
	if(relativeY < 132) return false;
	
	var url;
	
	//previous
	if(e.pageX < 180){
		if(e.pageY < 100) return false;
		url = $("#subnavLeft").attr('href');
		if(url==null)return;
		window.location = url;
		e.preventDefault();
		return false;
	
	//next
	} else if ($(window).width() - e.pageX < 180  && $("#subnavRight").attr('href')!=null) {
		
		e.preventDefault();
		//$('a.cloud-zoom').unbind('click');
		
		url = $("#subnavRight").attr('href');
		//if(url==null)return;
		window.location = url;
		return false;
		
	//photo click	
	} else if (detailOverImage(e.pageX)) {
		//zoom
		
		e.preventDefault();
		$('a.cloud-zoom').trigger({type:"myclick"});
		
	
	//styleswitcher
	} else {
		
		if($.stylesheets.alternateOn()){
			$.stylesheets.clear();
		} else {
			$.stylesheets.clear().add("css/alternative.css");
		}
	}
}

function detailMousePage(e){
	window.clearTimeout(mousemove_timeout);
	mousemove_timeout = null;
	
	var relativeX = $(window).width() - e.pageX;
	var relativeY = $(window).height() - e.pageY;
	
	//cursor 
	var cursor = "default";
	var imgCursor = "default";
	//left side 
	if(relativeY > 132 && (e.pageX < 180 && e.pageY > 100) &&  $("#subnavLeft").attr('href')!= undefined){
		 cursor = "url(img/arrow_left.png) 0 0, pointer";
	//right side
	} else if(relativeY > 132 && ($(window).width() - e.pageX < 180) &&  $("#subnavRight").attr('href')!= undefined){
		 cursor = imgCursor = "url(img/arrow_right.png) 0 0, pointer";
	} else if (catId!=74) { //not news detail & not art shop detail
		//over the image?
		if(detailOverImage(e.pageX) && $.fn.CloudZoom()!=null && $.fn.CloudZoom().isBigEnough()) imgCursor = "url(img/zoom.png) 0 0, crosshair";
	}
	$("#detail").css("cursor", cursor);
	
	
	$('#detailImg').css("cursor", imgCursor);
	
	var gotoY = -180; 	
	//bottom part of screen?
	if(relativeY < 200){
		gotoY = 0;
		//is er een carousel?
		if($('#carousel').length > 0) gotoY = 100;
	}
	
	var currentPos =  $('#overLayer').css("bottom");
	if(currentPos==gotoY) return;
	
 	
	$('#overLayer').stop().animate({ "bottom": gotoY + "px" }, 300);
}

function detailOverImage(pageX){
	
	//video
	if($('#detailImg').length == 0) return false;
	
	var imgX1 =  $('#detailImg').offset().left;
	var imgX2 = imgX1 + $('#detailImg').width();
	
	//also check if not at the border
	return (pageX > imgX1 &&  pageX < imgX2);
}
function placeDetail(){
	
	var w = $('#detailImg').width();
	
	if(!(w > 10) || detailLoaded) return;
	
	//different for video or image
	if($(".videoWrapper").length > 0){
		//video: center
		$('#overLayer .info').css('left', '50%');	
		$('#overLayer .info').css('marginLeft', '-450px');
		
		//$video = ($("#detailImg").is('.videoWrapper'));
		
	} else {
		$('#loading').remove();
		
		//big image
		//random placement on the righht
		var leftMargin = (catId==94)? 250:180;
		var endPos = $(window).width() - $('#detailImg').width()-leftMargin;	
		var randPos = leftMargin + Math.ceil(Math.random()*endPos);
		randPos = Math.max(leftMargin, randPos);
		$('#detailImg').css('left', randPos);
		$('#overLayer .info').css('left', randPos+10);		
	}
	
	resizeDetail();
	
	$('#detailImg').fadeIn("slow");
	
	detailLoaded = true;
	
	//2d time for chrome
	resizeDetail();
}

function resizeDetail(){
	
	//adjust the image if offscreen
	var offScreen = $('#detailImg').position().left + $('#detailImg').width() - $(window).width();
	
	//console.log("offScreen=" +offScreen);
	
	var ratio = $('#detailImg').width()/$('#detailImg').height();
	var newH = Math.min(($('#detailImg').width() - offScreen) /ratio, $(window).height());
	$('#detailImg').height( newH );
	
	$('#detailImg').not(".videoWrapper").css("top", ( $(window).height() - newH )/2);	
	$('#overLayer .info').width($('#detailImg').width()-65);
	
	
}

function newsInit(){
	 //we can click on the whole news block
	 $('#news .td2, #news .td3').click(function(e) {
		var url = $(this).parent().find("h2 a").attr('href');
		if(url==null) return;
		window.location = url;
		e.preventDefault();
	 });
	 
	  //make sure we can still click on the links
	 $('#news a').bind('click', function(e){
		e.stopPropagation();
     });
	 
	 //tooltips
	simple_tooltip("#news a","tooltip");
}

function newsDetailInit(){
	
	//images loaded for chrome
	$(window).load(function() {
		resizeNewsDetail();
	});
	//resizing
	$(window).bind("resize", function(){
		resizeNewsDetail();
    });
	resizeNewsDetail();
	
	$('#detailImg').fadeIn("slow");
	
	/*$('body').click(function(e) {
		detailClickPage(e);
	});	
	*/
	//show cursor
	window.clearTimeout(mousemove_timeout);
	$('body').mousemove(function(e) {
		if (mousemove_timeout == null) mousemove_timeout = window.setTimeout(function(){detailMousePage(e)}, 150);
		//if (mousemove_timeout == null) mousemove_timeout = window.setTimeout(function(){detailMousePage(e)}, 150);
	});
	
	$('body').click(function(e) {
		newsDetailClickPage(e);
	});
}

function resizeNewsDetail(){
	$('#detailImg').height( $(window).height() - $('#newsOverLayer').height() - 40);
}

function newsDetailClickPage(e){
	
	var relativeY = $(window).height() - e.pageY;
	var url;
	
	//previous
	if(e.pageX < 180){
		if(e.pageY < 100) return false;
		url = $("#subnavLeft").attr('href');
		if(url==null)return;
		window.location = url;
		e.preventDefault();
		return false;
	
	//next
	} else if ($(window).width() - e.pageX < 180) {
		
		e.preventDefault();
		//$('a.cloud-zoom').unbind('click');
		
		url = $("#subnavRight").attr('href');
		if(url==null)return;
		window.location = url;
		return false;
	}
}


function carouselInit(){	
	
	$('#carousel').show();
	$('#carousel').jcarousel();	 
}

function favoritesInit(){
	$('a.remove').click(function(e){
		$(this).parent().data("old", $(this).parent().html());
		$(this).parent().html('remove? &nbsp;&nbsp;<a href="javascript:void(0);" onclick="favoriteRemove(this)" class="cancelyes">yes</a> - &nbsp;&nbsp;<a href="javascript:void(0);" onclick="favoritesCancel(this)" class="cancelyes">no</a>');
		e.preventDefault();
	});
}
function favoritesCancel(obj){
	$(obj).parent().html($(obj).parent().data("old"));
	favoritesInit();
}
function favoriteRemove(obj){	
	
	var alias = $(obj).parent().parent().find("a").attr('href').split("/")[1];
	
	$.ajax({ 
		url: "_include/favorize-del.php?a="+alias,
		success: function(data){
			$(obj).parent().parent().animate({'width':'1px'}, 400, function(){ $(obj).parent().parent().remove(); } );
		}
	});
}

function favorize(alias){
	
	$.ajax({ 
		url: "_include/favorize.php?a="+alias,
		success: function(data){
			//alert(data);
			//not logged in
			if(data==-1) $(location).attr('href', window.location.pathname + "../../my-favorites/login/?al="+alias);
			if(data==1) $("#overLayer .info a.favorize"	).html("favorized!");
		}
	});
}

function customScrollbar(){
	var win = $(window);
	// Full body scroll
	var isResizing = false;
	win.bind(
		'resize',
		function()		{
			if (!isResizing) {
				isResizing = true;
				var container = $('#wrapper');
				// Temporarily make the container tiny so it doesn't influence the
				// calculation of the size of the document
				container.css(
					{
						'width': 1,
						'height': 1
					}
				);
				// Now make it the size of the window...
				container.css(
					{
						'width': win.width(),
						'height': win.height() - 500
					}
				);
				isResizing = false;
				container.jScrollPane(
					{
						'showArrows': false
					}
				);
			}
		}
	).trigger('resize');

	// Workaround for known Opera issue which breaks demo (see
	// http://jscrollpane.kelvinluck.com/known_issues.html#opera-scrollbar )
	$('body').css('overflow', 'hidden');

	// IE calculates the width incorrectly first time round (it
	// doesn't count the space used by the native scrollbar) so
	// we re-trigger if necessary.
	if ($('#wrapper').width() != win.width()) {
		win.trigger('resize');
	}

	// Internal scrollpanes
	/*$('.scroll-pane').jScrollPane({
		showArrows: false
	});*/
}


function shareIt(id, titleStr, linkStr){
	
	var t = (titleStr.length>4)? titleStr:document.title;
	var u = (linkStr.length>10)? linkStr:location.href;
		
	//u += "?st=6"
	//var u = "www.atlasreizen.be/mensen/wiet-proesmans/";
	
	var url = "";
	var w = 700;
	
	switch(id) {
		case 10: //twitter
			url = "http://twitter.com/home?status=" + encodeURIComponent(t);// +" " + u.replace("#", "%23");
			w = 800;
			break;
		case 20: //facebook
			//url = "http://www.facebook.com/sharer.php?u="+ encodeURIComponent(u);// +"&t="+encodeURIComponent(t);
			url = "http://www.facebook.com/sharer.php?u="+ encodeURIComponent(u) +"&t="+encodeURIComponent(t);
			//url = "http://www.facebook.com/sharer.php?u="+u;
			//url = "http://www.facebook.com/share.php?u=" + encodeURIComponent(u);
			break;
	}
	
	window.open(url,'sharer','toolbar=0,status=0,width='+w+',height=436');
}

function simple_tooltip(target_items, name){
 
	$(target_items).each(function(i){

		if($(this).attr("title") != ""){ 
		
			//check exits?
			if( $("#"+name+i).length > 0) return;
		
			var cname = (Math.random()<.5)? " black":"";
			$("body").append("<div class='"+name+cname+"' id='"+name+i+"'><p>"+$(this).attr('title')+"</p></div>");
			var my_tooltip = $("#"+name+i);

			$(this).removeAttr("title").mouseover(function(){
					my_tooltip.css({opacity:1, display:"none"}).fadeIn(300);
			}).mousemove(function(kmouse){
					my_tooltip.css({left:kmouse.pageX+15, top:kmouse.pageY+15});
			}).mouseout(function(){
					my_tooltip.fadeOut(250);
			});
		}
	});
}

function listingInit(){
	
	//infinity sroll
	$(document).endlessScroll({
	    fireOnce: true,
	    fireDelay: 2000,
	    loader: '<div class="loading"><div>',
	    callback: function(i){
	        //console.log("loader" + i);
			$.ajax({
                url: (catId<80)? "_include/getMoreItems.php?i=":"_include/getMoreShop.php?i=" + i,
                success: function(html){
                    if(html){
                        $("#listing").append(html);
						
						simple_tooltip("#listing .img:hidden a","tooltip");
						
						//console.log($(html));
						$("#listing .img:hidden").each(function(index) {
							
							$(this).hide().delay(100*index).fadeIn(300);
						});
						
                        $('div#loadmoreajaxloader').hide();
                    } else{
                        $('div#loadmoreajaxloader').html('<center>No more photos to show.</center>');
                    }
                }
            });
	    }
	});
	
	
}
