jQuery.fn.extend({
  slideRightShow: function() {
    return this.each(function() {
        $(this).show('slide', {direction: 'right'}, 1000);
    });
  },
  slideLeftHide: function() {
    return this.each(function() {
      $(this).hide('slide', {direction: 'left'}, 1000);
    });
  },
  slideRightHide: function() {
    return this.each(function() {
      $(this).hide('slide', {direction: 'right'}, 1000);
    });
  },
  slideLeftShow: function() {
    return this.each(function() {
      $(this).show('slide', {direction: 'left'}, 1000);
    });
  }
});

$(function() {

	$('.target_blank, .blank, .external').attr('target','_blank');

});

$(function() {

	// Remove address and switch to hashtag
	if (document.location.pathname != '/') {
		//document.location = '/#'+document.location.pathname;
	}

});

var initTopBio = null;
var initTopInfosPictures = null;
var initTopCategory = null;
var reloadContext = null;

function getCurrentPhotoId() {
	if (currentPictureId != false) {
		return currentPictureId;
	} else 
	if ($('#block_imgs a.on').length > 0) {
		var id = parseInt($('#block_imgs a.on').attr('id').substr(6));
		return id;
	} 
	else {
		return pictureSetIndex[0];
	}
}

function getCurrentPhotoIndex() {
	if ('indexOf' in pictureSetIndex) {
		// Firefox, Chrome, Safari, etc.
		return pictureSetIndex.indexOf(getCurrentPhotoId());
	} else {
		// Internet Explorer
		var id = getCurrentPhotoId();
		for (var i=0;i<pictureSetIndex.length;i++) {
			if (pictureSetIndex[i] == id) {
				return i;
			}
		}
		return 0;
	}
}

function gotoNextPhoto() {
	var idx = getCurrentPhotoIndex();
	if (idx < pictureSetIndex.length-1) {
		gotoPhoto(pictureSetIndex[idx+1]);
	} else {
		gotoPhoto(pictureSetIndex[0])
	}
}

function gotoPreviousPhoto() {
	var idx = getCurrentPhotoIndex();
	if (idx > 0) {
		gotoPhoto(pictureSetIndex[idx-1]);
	} else {
		gotoPhoto(pictureSetIndex[pictureSetIndex.length-1]);
	}
}

function gotoPhoto(id) {
	// Do nothing if picture unknown
	if (!(id in pictureSet)) return;
	
	// Clear current photo
	$('#block_imgs a.on').removeClass('on');
	$('#background').attr('id','background_old');
	$('<img />')
		.attr('src','/wp-content/themes/patricedion/images/empty.gif')
		.attr('id', 'background')
		.css({
			display:'inline',
			opacity:0
		})
		.addClass('fullBg')
		.insertAfter($('#background_old'));
	$('#background_old').remove();
	
	// Set new photo
	currentPictureId = id;
	$('#block_imgs a#photo-'+id).addClass('on');
	$('#background').css({
		width:pictureSet[id].size[0]+'px',
		height:pictureSet[id].size[1]+'px'
	});
	$('#background').attr('src',$('#block_imgs a#photo-'+id).attr('rel'));
	$("#background").fullBgUpdate();
	$("#background").css({opacity:1});
	
	// Update info box
	$('#block_infosPictures .title').text(pictureSet[id].title);
	$('#block_infosPictures .desc').html(pictureSet[id].description);
	var dateLoc = [];
	if (pictureSet[id].date != '') dateLoc.push(pictureSet[id].date);
	if (pictureSet[id].location != '') dateLoc.push(pictureSet[id].location); 
	$('#block_infosPictures .date_location').html(dateLoc.join('<br/>'));
	Cufon.refresh();
}

$( document ).ready(function () {
	/**********************************************************/
	$(function() { //

		$("#trigger_bgs_container").click(function(){

			if( $(this).hasClass('up') ){
				$(this).removeClass('up');
				$("#block_pictures").animate({top : '-29px'}, 500, 'easeInQuart');
			}else{
				$(this).addClass('up');
				$("#block_pictures").animate({top : '73px'}, 400, 'easeOutQuad');
			}

			$(this).trigger('blur');

		});


	});// end ::
	/**********************************************************/
	

	/**********************************************************/
	initTopInfosPictures = function() { //
		
		var initTop = '-'+$("#block_infosPictures").height()+'px';
		$("#block_infosPictures").css('top', initTop );
		$("#navigation .infos a").click(function(){
			if( $(this).hasClass('up') ){
				$(this).removeClass('up');
				var initTop = '-'+$("#block_infosPictures").height()+'px';
				$("#block_infosPictures").animate({top : initTop}, 250, 'easeInQuart');
				Cufon.refresh();
			}else{
				$(this).addClass('up');
				$("#block_infosPictures").animate({top : '73px'}, 500, 'easeOutQuad');
				Cufon.refresh();
			}

			$(this).trigger('blur');
		});
		
		$("#block_infosPictures").click(function(){
			$("#navigation .infos a").trigger('click');
		});
		
	};// end ::
	/**********************************************************/

	
	/**********************************************************/
	initTopCategory = function() { //
		
		$(".category-menu a")
			.attr('href','javascript:void(0)')
			.click(function(){
				reloadContext($(this).attr('rel'));
				$(".category-menu a").removeClass('up');
				$(this).addClass('up');
				Cufon.refresh();
			});

		$("h1 a")
			.attr('href','javascript:void(0)')
			.click(function(){
				reloadContext();
				$(".category-menu a").removeClass('up');
				Cufon.refresh();
			});
		
		reloadContext = function(category) {
			$('#background').css({opacity:0});
			$('#block_imgs a').remove();
			
			var url = '/webservice/context';
			if (typeof category != 'undefined') url += '?category='+encodeURIComponent(category);
			$.ajax({
				url: url,
				dataType: 'json',
				success: function(data, textStatus, jqXHR) {
					// Success
					pictureSet = {};
					for (var n=0;n<data.pictureSetIndex.length;n++) {
						var i = data.pictureSetIndex[n];
						var j;
						if (typeof i != 'number') j = parseInt(i);
						else j = i;
						pictureSet[j] = data.pictureSet[i];
					}
					pictureSetIndex = data.pictureSetIndex;
					
					for (var n=0;n<data.pictureSetIndex.length;n++) {
						var i = data.pictureSetIndex[n];					
						var newImage = $('<a id="photo-'+i+'"><img /></a>');
						newImage
							.attr('rel',pictureSet[i].image)
							.attr('href','javascript:void(0)')
							.attr('title',pictureSet[i].title);
						newImage.find('img')
							.attr('src',pictureSet[i].thumbnail)
							.attr('width',23)
							.attr('height',45)
							.attr('alt',pictureSet[i].title);
						newImage.appendTo("div.block_imgs_container");
					}
					doSetupImgs();

					gotoPhoto(pictureSetIndex[0]);
				},
				error: function(jqXHR, textStatus, errorThrown) {
					//console.log('Error: '+textStatus);
					//console.log(errorThrown);
				}
			});
		};
		
	};// end ::
	/**********************************************************/
	

	/**********************************************************/
	initTopBio = function() { //
		
		$("#navigation li.page-menu").each(function(){
			$(this).find('a').attr('href','javascript:void(0)');
			$(this).find('a').click(function(){
				var page_id = $(this).parent().attr('id').substr(10);
				
				if( $(this).hasClass('up') ){
					$(this).removeClass('up');
					var initTop = '-'+$("#page-"+page_id).height()+'px';
					$("#page-"+page_id).animate({top : initTop}, 250, 'easeInQuart');
					Cufon.refresh();
				}else{
					// Close open page
					var opened = $("#navigation li.page-menu a.up");
					if (opened.length > 0) {
						// Switch menu classes
						opened.removeClass('up');
						$(this).addClass('up');
						Cufon.refresh();
						
						//
						var nid = opened.parent().attr('id').substr(10);
						var initTop = '-'+$("#page-"+nid).height()+'px';
						$("#page-"+nid).animate({top : initTop}, 250, 'easeInQuart', function(){
							// Open new one once the old one is closed
							$("#page-"+page_id).animate({top : '73px'}, 500, 'easeOutQuad');
							
							// Open new one
							$('#page-menu-'+page_id+' a').addClass('up');
							
							Cufon.refresh();
						});
					} else {
						// Open new one right away
						$("#page-"+page_id).animate({top : '73px'}, 500, 'easeOutQuad');
						
						// Switch menu classes
						$(this).addClass('up');
						Cufon.refresh();
					}
				}
				$(this).trigger('blur');
			});
		});
		
		$('div.block_page div.clickmask').click(function(){
			var page_id = $(this).parents('div.block_page').attr('id').substr(5);
			$('#page-menu-'+page_id+' a').trigger('click');
		});
		
	};// end ::
	/**********************************************************/


});

var doSetupImgs = null;

$( window ).load(function () {

	/**********************************************************/
	$("#background").fullBg();
	$("#background").css('opacity',1);
	
	//$("#wrapper").height( $(window).height() );
	/**********************************************************/


	/**********************************************************/
	doSetupImgs = function(){

		var width_img = 37;
		var block_imgs_width = $("#block_imgs").width();
		var num_imgs_by_line = Math.floor( block_imgs_width / width_img);
		var num_imgs = $("#block_imgs .block_imgs_container a").length;
		var current_line = 0;
		var max_lines = Math.ceil( num_imgs / num_imgs_by_line );

		for( var i=0;i<max_lines;i++ ){
			$('#block_imgs .block_imgs_container a:lt(' + num_imgs_by_line + ')').clone().prependTo('#block_imgs .block:eq(' + i + ')');
			$('#block_imgs .block_imgs_container a:lt(' + num_imgs_by_line + ')').remove();
		}
		$('#block_imgs .block_imgs_container').empty();
		$('#block_imgs .block').width( block_imgs_width );

		$('#block_imgs a')
			.attr('href','javascript:void(0)')
			.click(function(){
				var id = $(this).attr('id').substr(6);
				gotoPhoto(id);
			});

		
		$('#block_imgs_prev').unbind('click');
		$('#block_imgs_next').unbind('click');
		$('#block_imgs .block:eq(0)').css({'margin-left':0});

		if( num_imgs > num_imgs_by_line ){

			$('#block_imgs_next').removeClass('off');

			$('#block_imgs_next').click(function(){

				if( $(this).hasClass('off') ){
					return false;
				}

				$('#block_imgs_prev').removeClass('off');

				//$('#block_imgs .block:eq(' + (current_line - 1 ) + ')').slideUp();
				current_line++;
				$('#block_imgs .block:eq(0)').animate({'margin-left':'-' + (current_line * block_imgs_width ) + 'px'}, 800);

				//$('#block_imgs .block:eq(' + (current_line - 1 ) + ')').slideRightShow();
				//$('#block_imgs .block:eq(' + (current_line - 1 ) + ')').slideDown();
				//$('#block_imgs .block:eq(' + (current_line - 1 ) + ')').animate({'margin-left':'150px'}, 1000);

				if( ( current_line + 1 ) >= max_lines ){
					$(this).addClass('off');
				}


			});

			$('#block_imgs_prev').click(function(){

				if( $(this).hasClass('off') ){
					return false;
				}

				$('#block_imgs_next').removeClass('off');

				//$('#block_imgs .block:eq(' + (current_line - 1 ) + ')').slideUp();
				current_line--;
				$('#block_imgs .block:eq(0)').animate({'margin-left':'-' + (current_line * block_imgs_width ) + 'px'}, 800);

				//$('#block_imgs .block:eq(' + (current_line - 1 ) + ')').slideDown();

				if( current_line <= 1 ){
					$(this).addClass('off');
				}

			});

		}else{
			$('#block_imgs_next').addClass('off');
		}
		$('#block_imgs_prev').addClass('off');
		
		// Bind arrow keys
		$(document).unbind('keydown');
		$(document).keydown(function(e){
			if (e.keyCode == 37) { 
				gotoPreviousPhoto();
				return false;
			}
			if (e.keyCode == 39) { 
				gotoNextPhoto();
				return false;
			}
		});
		// Bind background mask
		$('#clickzone .left').unbind('click');
		$('#clickzone .left').click(function(){
			gotoPreviousPhoto();
		});
		$('#clickzone .right').unbind('click');
		$('#clickzone .right').click(function(){
			gotoNextPhoto();
		});

	};
	doSetupImgs();
	/**********************************************************/

	/**********************************************************/
	initTopBio();
	initTopInfosPictures();
	initTopCategory();
	/**********************************************************/

});







