/**
	HT is the global namespace container
	@requires jQuery.js
	@namespace
*/

var HT = (function($) {

	var templateURL = '';

	/**
		Blah blah blah
		@name general
		@memberOf HT
		@namespace
	*/
	var general = {
		/**
			Set site globals
			@private
		*/
		init: function() {
			general.setGlobals();
		},
		/**
			Set site globals
			@private
		*/
		setGlobals: function() {
			$('a[rel=external]').attr('target','_blank');
			$('a[href=#]').click( function(e) { e.preventDefault() }) ;
		}
	};
	
	/**
		Handling of the search toggling
		@name searchBar
		@memberOf HT
		@namespace
	*/
	var searchBar = {
	
		defaultText: 'Search',
		input: false,
	
		/**
			Initialize the search bar
			@private
		*/
		init: function() {
			searchBar.input = $('#header input[name=s]');
			searchBar.checkValue();
			searchBar.input.live('blur', function(e) {
				searchBar.checkValue('blur');
			});
			searchBar.input.live('focus', function(e) {
				searchBar.checkValue('focus');
			});
			$('.searchform').submit( function() {
				if ( searchBar.validates() ) {
					return true;
				} else {
					alert('Oops. Try again.');
					return false;
				}
			});
		},
	
		/**
			Check the value of the input
			@private
		*/
		checkValue: function(t) {
			var v = $.trim( searchBar.input.val() );
			if (t=='focus') {
				if (v == searchBar.defaultText) searchBar.input.val('');
			} else {
				if (v == '') searchBar.input.val( searchBar.defaultText );
			}
		},
	
		/**
			Validate the form
			@private
		*/
		validates: function() {
			var v = $.trim( searchBar.input.val() ).toLowerCase();
			if ( v == '' || v == searchBar.defaultText.toLowerCase() ) {
				return false;
			} else {
				return true;
			}
		}
		
	};
	
	/**
		Flyout functionality for the calendar / tags layer
		@name flyout
		@memberOf HT
		@namespace
	*/
	var flyout = {
	
		window	     : '',
		offset		 : 0,
		processing   : false,
		timer        : false,
		keepVisible  : false,
		inTransition : false,
		isShowing	 : false,
		backOn       : false,
		
		/**
			Initialize the flyout
			@private
		*/
		init: function() {
		
			flyout.setBrowser();

			flyout.window = $('#flyout');
			flyout.offset = flyout.window.height();
			flyout.window.css( 'marginTop', -flyout.offset+10 );

			$('#icn-pull-tab').click( function(e) {
				e.preventDefault();
				flyout.react();
			});
			
			
		},
		
		/**
			Display the flyout
			@private
		*/
		react: function() {
			
			if ( flyout.isShowing ) {
				flyout.window.animate({ marginTop : -flyout.offset+10 })
				flyout.isShowing = false;
			} else {
				flyout.window.animate({ marginTop : 0 })
				flyout.isShowing = true;
			}

		},
		
		
		/**
			Sets the browser mechanism
			@private
		*/
		setBrowser: function(x) {
			var $b  = $('.browseform'),
				$ul = $b.find('ul').hide();
			$b.find('.toggler').toggle(
				function() {
					$ul.fadeIn('fast');
				},
				function() {
					$ul.fadeOut('fast');
				}
			);
		}
		
	};

	/**
		Load more functionality to show more posts
		@name flyout
		@memberOf HT
		@namespace
	*/
	var loadMore = {
	
		/**
			Initialize the app functions
		*/
		init: function() {
		
			var theOos = 'o';
			
			$('#content').infinitescroll({
				loading  : {
					finishedMsg : "Sorry, no more",
					msgText     : "Loading m"+theOos+"re...",
					img         : HT.templateURL + "/images/gra-loader.gif"
				}
			}, function() {
				theOos = theOos + 'oo';
/*
				console.log( $.data(this, 'infinitescroll') );
				$.data(this, 'infinitescroll').update({
					loading  : {
						msgText     : "Loading m"+theOos+"re..."
					}
				});
*/
			});
  			
		}
		
	};
	
	/**
		Handling of the comments
		@name comments
		@memberOf HT
		@namespace
	*/
	var comments = {
	
		respondDiv  : '',
		currentPost : '',
	
		/**
			Initialize the comments on the page
			@private
		*/
		init: function() {
			
			comments.respondDiv = $('#respond');	
			comments.setValidation();
		
			$('p.comment-count a').live( 'click', function(e) {
				e.preventDefault();
				var $this = $(this),
				    $p = $this.parents('.post'),
				    pid = $p.attr('id'); 

				if ( comments.currentPost == pid ) {
					if ( comments.respondDiv.is(':visible') ) {
						comments.close();
					} else {
						comments.respondDiv.fadeIn();
					}
				}  else {
					comments.respondDiv.hide();
					$p.find('.extras').append(comments.respondDiv);
					comments.respondDiv.fadeIn();
					comments.assignVals($p);
				}
				
			});
			
			$('#commentform a.closer').live('click', function(e) {
				e.preventDefault();
				comments.close();
			});

		},
	
		/**
			Assign the values for the comment
			@private
		*/
		assignVals: function( $post ) {
			
			var pid = $post.attr('id'),
			    n = Number( pid.split('-')[1] );
			comments.respondDiv.find('#comment_post_ID').val( n );
			comments.currentPost = pid;
			
		},
	
		/**
			Close comment box
			@private
		*/
		close: function() {
			comments.respondDiv.fadeOut( function() {
				$(this).find('input[type=text], textarea').each( function() {
					$(this).val('');
				});

			});
		},
	
		/**
			Display error
			@private
		*/
		displayError: function(xhr) {
			var $r = $(xhr.responseText);
			var msg = ($.browser.mozilla) ? $r[9] : $r[4];
			alert( 'Sorry... ' + $(msg).text() );
		},
	
		/**
			Update comments
			@private
		*/
		updateComments: function(data) {
			comments.close();
			// parse response
			$r = $(data);
			cPost = '#'+comments.currentPost;
			$p = $r.find(cPost);
			$c = $p.find('.comments');
			// update comment list
			$thanks = $('<p class="thanks">Thanks for the comment!</p>');
			$(cPost).find('.comments').replaceWith($c);
			$(cPost).find('.extras').append($thanks);
			setTimeout(
				function() {
					$thanks.fadeOut()
				},
				3000
			);
		},
	
		/**
			Validate comment box
			@private
		*/
		setValidation: function() {
		
			comments.respondDiv.find('#commentform').validate({
			
/*
				errorPlacement: function(error, element) {
					//element.parents('fieldset').addClass('error');
					//error.appendTo( element.parents('fieldset') );
				},
*/
				
				showErrors: function(errorMap, errorList) {
					comments.respondDiv.find('fieldset').removeClass('error');
					$.each( errorList, function(k, v) {
						$(v.element).parents('fieldset').addClass('error');
					});
					this.defaultShowErrors();
				},

				rules: {
					// simple rule, converted to {required:true}
					name: {
						required: true
					},
					email: {
						required: true,
						email: true
					},
					comment: {
						required: true
					}
				},
			
				messages: {
					'author': {
						required: "Please enter your name",
						maxlength: "Too many characters (50 allowed)"
					},
					'email': {
						required: "Please enter a valid email address",
						maxlength: "Too many characters (70 allowed)"
					},
					'url': {
					},
					"comment": {
						required: "Please enter your comment"
					}
				},
				
				/**
					clean comments
					@private
				*/
/*
				cleanConfirmation: function() {
					//$('#confirmation-message').removeClass('error').removeClass('success');
					$('#confirmation-message p').remove();
				},
				
*/
				submitHandler: function( form ) {
					$f = $(form);
					$f.ajaxSubmit({
						url    : $f.attr('action'),
						type   : 'post',
						data   : $f.serialize(),
						success: function(data) {
							comments.updateComments(data);
						},
						error: function(XMLHttpRequest, textStatus, errorThrown) {
							comments.displayError(XMLHttpRequest);
						}
					});
				}
			
			});
			
			
			
		}
		
	};
	
	/**
		return for public functions
	*/
	return {
		
		init: function( url ) {
			this.templateURL = (url != '') ? url : '/';
			general.init();
			searchBar.init();
			flyout.init();
			loadMore.init();
			comments.init();
		}
	
	}

	

})(jQuery);
