var Directory = document.location.href.match(/^http:\/\/[^/]+\/([^#\?\/]+)/);
if (Directory != null) {
	Directory = Directory[1];
}

var	bodyClass, bodyId, frontpage, horizontal;

function insert_twitter(){
	new TWTR.Widget({
	  version: 2,
	  type: 'profile',
	  rpp: 4,
	  interval: 6000,
	  width: 500,
	  height: 300,
	  theme: {
		shell: {
		  background: 'transparent',
		  color: 'black'
		},
		tweets: {
		  background: 'transparent',
		  color: '#666',
		  links: 'black'
		}
	  },
	  features: {
		scrollbar: false,
		loop: false,
		live: false,
		hashtags: true,
		timestamp: true,
		avatars: false,
		behavior: 'all'
	  }
	}).render().setUser('adamlebor').start();
}

function ucfirst(str){
	return str.charAt(0).toUpperCase() + str.slice(1);
}

window.addEvent('domready', function() {
	bodyClass = $(document.body).get('class');
	bodyId    = $(document.body).get('id');
	frontpage = ( bodyClass == 'home' && bodyId == 'index');

	if (Directory != null) {
		// Add it to the main title
		document.title = document.title.replace(/adam lebor:?\s*/i, "Adam LeBor - " + Directory +" - ");	
		// Nav:
		if ($( Directory )) $( Directory ).addClass('active');
		if (Directory == 'journalism'){
			var h3 = $('promo-main').getFirst('h3');
			h3.set('text', ucfirst( Directory ) +': '+ h3.get('text') );
		}
	}

	new Tips('.tip',{
		className: 'mytip',
		text: ''
	});
	
	// Perl added a link, use it to wrap content:
	$$('div#promo-columns .this_uri', 'div#promo-main .this_uri').each( function(i){
		var a = new Element('a', {
			href: i.get('href'),
			'class': 'tip',
			title: 'Click to read more'
		}).wraps( i.getParent() );
	});
	
	// $('bio-link').addEvent("click", function() { new baseBox.lightBox( '/bio/adam_lebor.jpg' ); });
	
	// Fade-out cropped text in promo columns
	$$('div#promo-columns div').each( function(i){
		new Element('div.fadeToWhite', {text:"Read More"}).inject( i )
	});
	
	// Swap titles and images in promo columns
	$$('div#promo-columns .third').each( function(i){
		i.getChildren('img').dispose().injectTop(i);
	});
	
	// Same for promo-main
	if (bodyClass != 'undef'){
		var a = new Element('div', {'class':'promo-main-fade'}).inject( $('promo-main') );
		var text = new Element('span', { 'class':'more', text: 'Read More' }).inject( a );
	}
	
	var splash = $$('#promo-main img');
	if (splash){
		var src = splash.get('src').toString().replace(/png$/, 'jpg');
		splash.set('src', src);
	}
	
	if (frontpage){
		new rssReadRender();
	}
});


	
var rssReadRender = new Class({
	container: null,
	initialize: function( args ){
		var self = this;
		self.container = $('blogger-posts');
		new Request.JSON({
			url: '/cgi-bin/get_rss.cgi?' + escape( 
				'http://adamlebor.blogspot.com/feeds/posts/default?max-results=7&alt=json'
			),
			evalScripts: false,
			onFailure: function(r){
				throw( 'Error getting get_rss.cgi: '+r.responseText );
			},
			onSuccess: function( json, txt ) {
				console.log(json);
				self.render(json)
			}
		}).get();
	},
	
	render: function(json){
		var self = this;
		if (!json) return;
		if (!json.feed) return;
		json.feed.entry.each( function( entry ){
			// Get the link 
			var href;
			for (var i=0; i<entry.link.length; i++){
				if (entry.link[i].type == 'text/html'
				&& entry.link[i].rel == 'alternate'
				){
					href = entry.link[i].href;
				}
			}
			var item = new Element('div', { 'class':'entry' }).inject( self.container );
			var a = new Element('a', { href: href }).inject( item );
			new Element('h5',  { text: entry.title.$t }).inject( a );
			new Element('p',  { 'class':'datetime', text: entry.published.$t }).inject( a );
			// new Element('div', { html: entry.content.$t }).inject( item );
		});
	}
});

var indexDirectory = new Class({
	container: null,
	initialize: function(args){
		var self = this;
		if (frontpage) return;
		if (!Directory) return;
		
		if (! args.container ) throw('No args.container supplied');
		this.container = $(args.container);
		if (! this.container ) throw('No '+args.container+' found for this.container found');
		if (1==1 && !frontpage
			&& ! location.href.match(/cgi-bin/)
		){
			new Request({
				url: '/' + Directory +'/order.txt',
				method: 'get',
				evalScripts: false,
				onFailure: function(r){
					// No order.txt found
					if (r.status==404) {
						if ( bodyClass == 'autoindex' ){
							self.layoutFromSelf(); 
						} else {
							// self.container.adopt( new Element('a', { href: '..', text: 'Back to the '+Directory+' index' }));
							self.layoutFromAutoindex();	
						}
					}
					else throw( 'Error getting order.txt: '+r.responseText );
				},
				onSuccess: function( txt ) {
					// No pics for Journalism, only Books
					if (document.location.href.indexOf('journalism')==-1)
						self.layoutList4Carouself( txt.split(/[\f\r\n]+/) );
					else
						self.layoutList( txt.split(/[\f\r\n]+/) );
				}
			}).send();
		}
		
/*		
		else {
			new Request({
				url: '/' + Directory +'/order.txt',
				method: 'get',
				evalScripts: false,
				onFailure: function(r){
					throw( 'Error getting doc: '+r.responseText );
				},
				onSuccess: function( txt ) {
					self.layoutList( txt.split(/[\f\r\n]+/) );
					// self.layoutFromHTML( as.get('html')[0] );
				},
			}).send();
		}
*/		
	},
	
	layoutList: function( list ){
		console.log(list);
		var self = this;		
		list.each( function( dir ) {
			if (dir && ! $(dir) ){
				var div = new Element('a', {
					'class': 'textOnly',
					href: '/'+Directory+'/'+dir,
					text: dir.replace( /_/g, ' ')
				});
				div.inject( self.container );
			}
		});
	},
	
	layoutFromSelf: function(){
		var dirs = [];
		$$('#autoindex a').each( function( a ){
			var m = a.get('href').match( /^([^\/]+)\/$/ );
			if (m) dirs.push( m[1] );
		});
		this.layoutList( dirs );
	},
	
	layoutFromAutoindex: function(){
		var self = this;
		new Request.HTML({
			url: '/' + Directory,
			method: 'get',
			evalScripts: false,
			onFailure: function(r){
				throw( 'Error getting /'+Directory+': '+r.responseText );
			},
			onSuccess: function( resTree, resElements, resHTML, resJavaScript ) {
				var dirs = [];
				var re = new RegExp( Directory + '/[^/]+/?$' );
				resElements.filter('a').each( function(i) {
					if ( i.href.match( re ) ){
						var dir = i.href.match( /([^#/]+)\/?$/ );
						if (dir) dirs.push( dir[1] );
					}
				});
				if (dirs.length) self.layoutList( dirs );
				else $('dirIndex').setStyle('display', 'none');
			},
		}).send();
	},
	

	layoutList4Carouself: function( list ){
		var self = this;		
		this.ctrlLeft = new Element('a', { id: 'ctrlLeft' }).inject( self.container );
		this.carousel = new Element('div', {
			id: 'carousel', 'class': 'carousel'
		}).inject( self.container );
		
		this.carouselInner = new Element('div', {
			id: 'carouselInner', 'class': 'inner'
		}).inject( self.carousel );
		
		this.ctrlRight = new Element('a', { id: 'ctrlRight' }).inject( self.container );
		
		list.each( function( dir ) {
			if (dir){
				title = dir.replace( /[-_]/g, ' ');
				var div = new Element('div', {
					'class': 'carouselEntry'
				});
				var a = new Element('a', { href: '/'+Directory+'/'+dir }).inject( div );
				new Element('img', { src: '/'+Directory+'/'+dir +'/book.png' }).inject( a );
				new Element('div', { 'class': 'label', text: title }).inject( a );
				div.inject( self.carouselInner );
			}
		});

		var width = 160 * list.length;
		self.carouselInner.setStyle('width', width );
		
		this.initCarousel();
	},
	
	initCarousel: function(){
		var self = this;
		self.horizontalCarousel = new Fx.Scroll.Carousel( self.carousel,{
			mode: 'horizontal'
		});
		self.ctrlRight.addEvent('click', function(){
			self.horizontalCarousel.toNext();
		});
		self.ctrlLeft.addEvent('click', function(){
			self.horizontalCarousel.toPrevious();
		});
	}
});















