/**
  * ADMINISTRATION
  **/
var administration = {
	createpost: {
		initialize: function() {
			administration.createpost.watchURLInput();
			administration.createpost.postType();
			var input = $$('input');
			var title_article = input[0],
				content_article = $$('textarea')[0];
			var title_blurb = input[3],
				content_blurb = $$('textarea')[1];
			administration.showcase.watch([title_blurb, content_blurb, 'blurb']);
			administration.showcase.watch([title_article, content_article, 'article']);
		},
		
		watchURLInput: function() {
			var url = $('url') ? $('url') : false;
			var title = $('title') ? $('title') : false;
			if(url && title) {
				title.addEvent('keypress', function() {
					// short delay for fetching value reasons
					window.setTimeout(function() {
						var prefix = 'http://chrisbuchholz.name/journal/';
						var sptitle = encodeURIComponent(title.get('value').toLowerCase()).replace(/\%20/g,'-').replace(/!/g,'').replace(/'/g,'').replace(/\(/g,'').replace(/\)/g,'').replace(/\*/g,'').replace(/\~/g,'');
						url.set('value', prefix+sptitle);
					}, 100);
				});
			}
		},
		
		postType: function() {
			var select = $('posttype') ? $('posttype') : false,
				articleForm = $$('form[name="article"]') ? $$('form[name="article"]') : false,
				blurbForm = $$('form[name="blurb"]') ? $$('form[name="blurb"]') : false;
			if(select && articleForm && blurbForm) {
				// hide non-default form
				var nondef = select.get('value') == 'article' ? 'blurb' : 'article';
				$$('form[name="'+nondef+'"]').setStyle('display', 'none');
				// onchange event for select
				select.addEvent('change', function() {
					if(this.value == 'article') {
						articleForm.setStyle('display', 'inline');
						blurbForm.setStyle('display', 'none');
					}
					else {
						articleForm.setStyle('display', 'none');
						blurbForm.setStyle('display', 'inline');
					}
					administration.showcase.wipe();
				}, this)
			}
		}
	},
	
	editpost: {
		initialize: function() {
			var input = $$('input');
			var title = input[0],
				content = $$('textarea')[0],
				type = $$('input')[5].get('value');
			administration.showcase.watch([title, content, type]);
			$$('button.delete').addEvent('click', function(event) {
				event.stop();
				administration.postDelete(type);
			});
		}
	},
	
	postListing: function() {
		$$('ul.adminPostListing > li').each(function(li) {
			li.addEvent('click', function() {
				var post_id = this.get('id').replace('post:', '');
				document.location.href = '/admin-edit-post/'+post_id;
			}, this);
		});
	},
	
	showcase: {
		watch: function(inputs) {
			var inputs = inputs;
			[inputs[0], inputs[1]].each(function(input) {
				input.addEvent('keyup', function() {
					administration.showcase.update(inputs);
				});
			});
			administration.showcase.update(inputs);
		},
		
		update: function(inputs) {
			var title = inputs[0].get('value').toLowerCase(),
				content = inputs[1].get('value'),
				type = inputs[2];
			var parent = !$('adminLivePostShowcase') ? new Element('div', {'id': 'adminLivePostShowcase'}) : $('adminLivePostShowcase');
			if(!$('adminLivePostShowcase'))
				$('content').grab(parent);
			// clear html
			while(parent.hasChildNodes()) parent.removeChild(parent.lastChild);
			// create html
			var article = new Element('article', {'class': 'post'});
			var h1 = new Element('h1', {'class': type});
			var a = new Element('a', {'text': title});
			content = content.replace(/\n/g, '<br />');
			content = new Element('p', {'html': content});
			var clearer = new Element('div', { 'class': 'clearer'});
			h1.grab(a);
			article.grab(h1);
			article.grab(content);
			article.grab(clearer);
			parent.grab(article);
		},
		
		wipe: function() {
			if($('adminLivePostShowcase')) {
				window.setTimeout(function() {
					$('adminLivePostShowcase').dispose();
				}, 10);
			}
		}
	},
	
	postDelete: function(type) {
		var post_id = $$('input')[3].value;
		if(confirm('Are you sure you want to delete this ' + type + '?'))
			document.location.href = '/admin-delete-post/' + post_id;
	},
	
	images: {
		initialize: function() {
			new jsupload($$('form')[0], administration.images.recieveImage);
		},
		
		recieveImage: function(data) {
		    if(data['error'] == '') {
		        var file = data['dir']+data['filename'];
		        var img = new Element('img', {'src': file});
		        $('adminPictureSlide').grab(img, 'top');
		    }
		    else
				alert(data['error']);
		}
	},
	
	post: {
		msg: function(str) {
			if($('stap'))
				var stap = $('stap');
			else {
				var stap = new Element('div', {
					'id': 'stap',
					'class': 'throwmsg',
				});
				$('content').grab(stap, 'top');
			}
			stap.set('html', str);
		},
		
		tweet: function(post_id) {
			administration.post.msg('posting tweet - hold on...');
			new Request({
				url: '/php/tweetpost.php',
				method: 'post',
				data: 'post_id=' + post_id,
				onSuccess: function(response) {
					administration.post.msg(response);
				},
				onFailure: function() {
					administration.post.msg('an error happened and the post was not tweeted');
				}
			}).send();
		}
	}
};

/**
  * calculated layout
  **/
var layout = {
	initialize: function() {
		var useragent = navigator.userAgent;
		var isipod = useragent.match(/ipod/i) != null,
			isiphone = useragent.match(/iphone/i) != null,
			isipad = useragent.match(/ipad/i) != null,
			isandroid = useragent.match(/android/i) != null;
		if(Browser.Engine.name == 'webkit' && !isipod && !isiphone && !isipad && !isandroid) {
			$(document.html).setStyle('overflow', 'auto');
			$(document.body).setStyles({
				'overflow-y': 'scroll',
				'overflow-x': 'hidden',
				'position': 'absolute'
			});
		}
	}
};


/**
  * INITIALIZER
  **/
window.addEvent('domready', function() {
	layout.initialize();
	new exTextarea();
});
