window.addEvent('domready', function() {

	var mySmoothScroll = new SmoothScroll({ duration: 1250 });
	var myScroll = new Fx.Scroll(window);
	
	var myURI = new URI(window.location);
	
	if(myURI.get('fragment') && myURI.get('fragment').match(/[a-zA-Z0-9_-]+\/[0-9]/)) {
		fragmentToPath().go();
	}
	
	var comicTitle	= $('comicTitle');
	var comicImage	= $('comicImage');
	var comicCat	= comicImage.get('rel');
	var comicInfo	= $('comicInfo');
	
	var commentNum	= $('commentNum');
	var commentList	= $('commentlist');
	var commentForm	= $('commentform');
	
	var comicNav	= $('comicNav');
	var comicNext	= $('comicNext');
	var comicPrev	= $('comicPrev');
	var comicLast	= $('comicLast')
	var comicFirst	= $('comicFirst');
	
	var href, src;
	
	function fragmentToPath() {
		if(myURI.get('fragment') && myURI.get('fragment').match(/[a-zA-Z0-9_-]+\/[0-9]/)) {
			var catID = myURI.get('fragment').split('/');
			return myURI.set('directory', '/'+catID[0]+'/').set('file', catID[1]).set('fragment', 'comic');
		}
		return myURI;
	}
	
	function num_comments(num) {
		if(num == 0) {return 'No Comments Yet';}
		else if(num == 1) { return '1 Comment';}
		else {return num+' Comments'}
	}
	
	function nl2p(text) {
		text = text.replace(/\r\n/g, '').replace(/\n+/g, '\n').replace('/^\s+$/g', '\s');
		text = '<p>'+text.split('\n').join('</p><p>')+'</p>';
		return text.replace(/<p>\s*?<\/p>/g, '').replace(/[\n\r]/g, '');
	}
	
	var comicAjax = new Request.JSON({
				url: '/php/ajax.php?form=comic&cat='+comicCat+'&referer='+document.location+'&rand='+Math.random(),
				method: 'get',
				onSuccess: function(json) {
					src = comicImage.get('src');
					comicImage.set('src', '/content/img/ajax-loader-dark.gif');
					errors.empty();
					errorFx.hide();
					if(json == null) {
						comicImage.set('src', src);
				//		alert('no response');
						href.toURI().set('fragment', 'comic').go();
					}
					else if(json.error && json.errors) {
						comicImage.set('src', src);
						$each(json.errors, function(error) {
				//			alert(error);
						});
						href.toURI().set('fragment', 'comic').go();
					}
					else {
						comicImage.set('src', json.image).set('title', json.desc).set('alt', json.alt).set('rel', json.cat);
						myScroll.toElement('comic');
						comicTitle.empty().set('html', '&ldquo;'+json.title+'&rdquo;');
						$(document.head).getElement('title').set('text', '#'+json.ID+' - '+json.title);
						commentNum.empty().set('text', json.commentsNum);
						comicInfo.empty().set('html', json.date+'<br />\nBy: <a href="#">'+json.authorFull+'</a>');
						myURI.set('fragment', json.category+'/'+json.ID);
						window.location.hash = '#'+json.category+'/'+json.ID;
						comicNav.empty().set('html', json.nav);
						
						$$('#comicNav a').addEvent('click', function(e) {
							e.stop();
							href = this.get('href');
							comicAjax.send('id='+this.get('rel'));
						});
						
						commentList.empty().set('html', '<h1>'+num_comments(json.commentsNum)+'</h1>');

						$each(json.comments, function(c, i) {
							var comm = new Element('div', {
								'class': 'comment',
								'id': 'comment-'+c.ID
							});
							var html = '<a name="comment-'+c.ID+'"></a><div class="commentAvatar"><img src="'+c.avatar_url+'" alt="" /></div><div class="commentBox"><div class="commentContent">'+nl2p(c.comment)+'</div><div class="commentAuthor"><span class="green">';
							if('' != c.website) { html += '<a href="'+c.website+'">'+c.name+'</a>'; }
							else { html += c.name; }
							html += '</span> on <a href="'+json.url+'" title="Permalink to this Comment">'+c.date+'</a></div></div>';
							comm.set('html', html);
							commentList.grab(comm);
						});
						
						$('PID').set('value', json.PID);
						
					}
				},
				onFailure: function() {
					alert('Failed to perform ajax query!');
				}
			});

	$$('#comicNav a').addEvent('click', function(e) {
		e.stop();
		href = this.get('href');
		comicAjax.send('id='+this.get('rel'));
	});


/********************************************
Comments Section
********************************************/

	var errorFx = new Fx.Slide('commentErrors', {duration:500}).hide();
	var errors = $('commentErrors');

	commentForm.addEvent('submit', function(e) {
		e.stop();
		var notice = 'HEY YOU!\n\n';
		var noticeLength = notice.length;
		if($('name') && $('name').value.length < 2) {
			notice += 'You forgot to leave your name!\n';
		}
		if($('comment').value.length < 2) {
			notice += 'You forgot to leave a comment!\n';
		}
		if($('security_code') && $('security_code').value.length < 4) {
			notice += 'You forgot to fill out the captcha code!\n';
		}
		if(notice.length != noticeLength) {
			alert(notice);
			return;
		}
		errors.empty().set('html', '<p><center><img src="/content/img/ajax-loader-dark.gif" /></center></p>');
		errorFx.show();
		commentForm.set('action', '/php/ajax.php?form=comment&referer='+fragmentToPath().toString());
		this.set('send', {
			onComplete: function() {
				if($('captcha')) {
					$('captcha').set('src', '/php/captcha.php?' + Math.random());
				}
				if($('security_code')) {
					$('security_code').set('value', '');
				}
			},
			onSuccess: function(html) {
				if('' != html) {
					var data = JSON.decode(html);
					if(data && data.error) {
						var errorsHTML = '';
						$each(data.errors, function(error) {
							errorsHTML += '<blockquote class="exclamation"><p>'+error+'</p></blockquote>';
						});
						errors.empty().set('html', errorsHTML);
						errorFx.slideIn();
					}
					else if('' != data.comment) {
						var div = new Element('div', {class: 'comment'});
						div.set('html', '<a name="comment-'+data.ID+'" id="comment-'+data.ID+'"></a> <div class="commentAvatar"><img src="'+data.avatar_url+'" alt="" /></div> <div class="commentBox"> <div class="commentContent">'+nl2p(data.comment)+'</div> <div class="commentAuthor"><span class="green">'+data.name+'</span> on <a href="#comment-'+data.ID+'" title="Permalink to this Comment">'+data.date+'</a></div> </div>');
						errors.empty().set('html', '<blockquote class="go"><p>Thanks for the comment!</p></blockquote>');
						errorFx.slideIn();
						commentList.grab(div, 'bottom');
						$('comment').set('value', '');
						myScroll.toElement(div);
						var num = commentNum.get('text').toInt()+1;
						commentNum.empty().set('text', num);
						commentList.getElement('h1').set('text', num_comments(num));
					}
				}
				else {
					errors.empty().set('html', '<blockquote class="stop"><p>Error Sending Request!</p></blockquote>');
					errorFx.slideIn();
				}
			},
			onFailure: function() {
				errors.empty().set('html', '<blockquote class="exclamation"><p>Failed to submit comment!</p></blockquote>');
				errorFx.slideIn();
			}
		});
		this.send();
	});

	var loginFx	= new Fx.Slide('loginForm', {duration:500}).hide();

	$$('.logInOut a').addEvent('click', function(e) {
		e.stop();
		if(this.innerHTML == 'Login') {
			if($('loginForm').get('html') == '') {
				$('loginForm').empty().set('html', '<p><span class="floatLeft">User: <input type="text" id="loginUser" value="" />Pass: <input type="password" id="loginPass" value="" /></span><span class="floatRight"><input type="submit" id="loginSubmit" value="Login" /><input type="button" id="loginCancel" value="Cancel" /></span></p>');
				$('loginSubmit').addEvent('click', function(e) {
					e.stop();
					loginAjax.send('user='+$('loginUser').get('value')+'&pass='+$('loginPass').get('value')+'&act=in');
				});
				$('loginCancel').addEvent('click', function(e) {
					e.stop();
					loginFx.slideOut();
				});
			}
			loginFx.slideIn();
		}
		else {
			if($('loginForm').get('html') == '') {
				$('loginForm').empty().set('html', '<p class="centerText">Are you sure you want to Logout?<br /><input type="button" id="logoutSubmit" value="Logout" /><input type="button" id="logoutCancel" value="Cancel" /></p>');
				$('logoutSubmit').addEvent('click', function(e) {
					e.stop();
					loginAjax.send('act=out');
				});
				$('logoutCancel').addEvent('click', function(e) {
					e.stop();
					loginFx.slideOut();
				});
			}
			loginFx.slideIn();
		}
	});
	
	var loginAjax = new Request.JSON({
			url: '/php/ajax.php?form=login&referer='+document.location+'&rand='+Math.random(),
			method: 'get',
			onSuccess: function(json) {
				if(json == null) {
					errors.empty().set('html', '<blockquote class="exclamation"><p>There was an error performing the ajax query.</p></blockquote>');
				}
				else if(!json.success && json.error) {
					errors.empty().set('html', '<blockquote class="exclamation"><p>'+json.error+'</p></blockquote>');
				}
				else {
					if('in' == json.act) {
						$('loginForm').empty().set('html', '<p><img src="'+json.avatar_url+'" alt="" /><span style="padding-left:10px;">Welcome, <span class="green">'+json.name+'</span>!</span></p>');
						$$('#logInOut a').set('text', 'Logout');
						if($('name')) { $('name').parentNode.dispose(); }
						if($('captcha') && $('security_code')) {
							$('captcha').dispose();
							$('security_code').dispose();
						}
					}
					else if('out' == json.act) { fragmentToPath().go(); }
				}
				errorFx.slideIn();
			},
			onFailure: function() {
				alert('Failed to perform ajax query!');
			}
		});

	$$('#smiliebox img').addEvent('click', function(e) {
		e.stop();
		$('comment').set('value', $('comment').get('value')+' '+this.get('alt')+' ').focus();
	});

	
});