(function($) {
	if (!JS_AB) { var JS_AB = new Object(); }
	
	JS_AB.abtv = 
	{
		debug : false,
		init : function() {
			JS_AB.abtv.hoverHandler.init();
			JS_AB.abtv.commentsHandler.init();
			JS_AB.abtv.quickSearchHandler.init();
			JS_AB.abtv.player.init();
			JS_AB.abtv.rating.init();
			JS_AB.abtv.popout.init();
			
			// counter
			if($('#counter').length > 0) JS_AB.abtv.counter.init();
		}
	}
	
	JS_AB.abtv.popout = 
	{
		init: function()
		{
			$('#showPopout').bind('click', function(e)
			{
				e.preventDefault();

				window.open($(this).attr('href'), $(this).attr('rel'), 
						'width=720,'+
						'height=418,'+
						'resizable=no,'+
						'scrollbars=no,'+
						'menubar=no,'+
						'status=no,'+ 
						'directories=no,'+
						'location=no,'+ 
						'toolbar=no'
				);
			});
		}
	}

	JS_AB.abtv.quickSearchHandler = 
	{
		minChars : 1,
		maxItemsToShow : 50,
		init : function() {
			if ($('#search, #searchAgain').length > 0) {
				$('#search, #searchAgain').autocomplete("/ajax.php?module=abtv&action=autocomplete", {
					matchContains : true,
					minChars : JS_AB.abtv.quickSearchHandler.minChars,
					dataType : 'json',
					maxItemsToShow : JS_AB.abtv.quickSearchHandler.maxItemsToShow,
					parse : JS_AB.abtv.quickSearchHandler._parseAutoComplete
				});
				$('#search, #searchAgain').result(JS_AB.abtv.quickSearchHandler._handleAutoComplete);
				$('#searchArtists, #searchAgain').bind('submit', function(evt) {
					evt.preventDefault();
					window.location = $(this).attr('action') + JS_NETLASH.utils.string.urlise($(this).find('#search, #searchAgain').val());
				});
			}
		},
		_parseAutoComplete : function(json) {
			if (JS_AB.abtv.debug)	console.log(json);
			var parsed = [];
			if (json.content.count > 0) {
				for (i in json.content.data) {
					var entryName 	= JS_NETLASH.utils.string.html_entity_decode(json.content.data[i].name);
					var entryUrl	= json.content.data[i].url;
					parsed[parsed.length] = {
						data	: [entryName],
						value	: entryUrl,
						result	: entryName
					};
				}
			}
			return parsed;
		},
		_handleAutoComplete : function(event, data, formatted) { if (formatted)	window.location = formatted; },
		_eoo : true
	}
	
	JS_AB.abtv.hoverHandler = 
	{
		init : function() {
			if ($('#abtv-images a').length > 0) {
				$('#abtv-images a').hover(
					function(evt) { 
						$('#row-' + $(this).attr('id').replace('image-', '')).addClass('hover'); 
						$(this).addClass('hover'); 
					},
					function(evt) { 
						$('#row-' + $(this).attr('id').replace('image-', '')).removeClass('hover'); 
						$(this).removeClass('hover'); 
					}
				);
				$('#abtv-datagrid tbody tr td').hover(
					function(evt) { 
						$('#image-' + $(this).parent('tr').attr('id').replace('row-', '')).addClass('hover');
						$(this).parent('tr').addClass('hover');
					},
					function(evt) { 
						$('#image-' + $(this).parent('tr').attr('id').replace('row-', '')).removeClass('hover'); 
						$(this).parent('tr').removeClass('hover'); 
					}
				);
			}
		},
		_eoo : true
	}
	
	JS_AB.abtv.commentsHandler = 
	{
		blob : '<div class="shoutbox-comment secondarycontent clearfix"><div class="avatar"><a href="{url}" class="noborder" title="{nick}"><img src="/modulefiles/profiles/avatars/48x48/{avatar}" alt="{nick}" title="{nick}" /></a></div><div class="message"><p class="user"><a href="{url}" title="{nick}">{nick}</a></p><p>{text}</p></div></div>',
		spinner : '<img src="/modules/core/layout/images/spinner.gif" id="spinner_{id}" alt="" title="" />',
		init : function() {
			if ($('#btnAddComment.abtv').length > 0) { $('#btnAddComment').removeAttr('disabled').bind('click', JS_AB.abtv.commentsHandler._initAddComment); }
			$('p.flagLink a').bind('click', JS_AB.abtv.commentsHandler._initFlagComment);
			$('p.deleteLink a').bind('click', JS_AB.abtv.commentsHandler.deleteComment);
		},
		_initAddComment : function(evt) {
			evt.preventDefault();
			$('#btnAddComment').attr('disabled','disabled');
			$('#spinner').css('visibility','visible');
			postData = $('#addCommentForm').serialize();
			JS_AB.abtv.commentsHandler._doAddComment(postData)
		},
		_doAddComment : function(postData) {
			console.log(postData);
			
			$.ajax({
				url: '/ajax.php?module=abtv&action=add_comment',
				type: 'post',
				dataType: 'json',
				cache: false,
				data: postData,
				success: function(json) { JS_AB.abtv.commentsHandler._doneAddComment(json); },
				error: function(xhr,err,e) {
					alert(err + ' ' + e, 'Critical Error');
					if(!JS_AB.abtv.debug) window.location.reload();
				}
			});
		},
		_doneAddComment : function(json) {
			if (JS_AB.abtv.debug) console.log(json);
			switch (parseInt(json.status.code)) {
				case 200:
				case 400:
					toInsert = JS_NETLASH.utils.string.assignFromObject(JS_NETLASH.utils.string.assignFromObject(JS_AB.abtv.commentsHandler.blob, json.content.user), json.content.comment);
					if (JS_AB.abtv.debug) console.log(toInsert);
					if ($('#no_sidebar_comments')) { $('#no_sidebar_comments').remove(); }
					$('#shoutbox-comments').prepend(toInsert);
					$('#addCommentForm').get(0).reset();
				break;
				case 500:
				default:
					alert(json.status.text);
				break;
			}
			$('#btnAddComment').removeAttr('disabled');
			$('#spinner').css('visibility','hidden');
		},
		_initFlagComment : function(evt) {
			evt.preventDefault();
			if (JS_AB.abtv.debug) console.log(evt);
			var id = evt.target.id.toString().substring(13);
			$(evt.target).parent().html(JS_NETLASH.utils.string.replaceAll(JS_AB.abtv.commentsHandler.spinner, '{id}', id));
			postData = 'comment_id=' + id;
			JS_AB.abtv.commentsHandler._doFlagComment(postData, id);
		},
		_doFlagComment : function(postData, id) {
			$.ajax({
				url: '/ajax.php?module=abtv&action=flag_comment',
				type: 'post',
				dataType: 'json',
				cache: false,
				data: postData,
				success: function(json) { JS_AB.abtv.commentsHandler._doneFlagComment(json, id); },
				error: function(xhr,err,e) {
					alert(err + ' ' + e, 'Critical Error');
					if(!JS_AB.abtv.debug) window.location.reload();
				}
			});
		},
		_doneFlagComment : function(json, id) {
			if (JS_AB.abtv.debug)	console.log(json);
			switch (parseInt(json.status.code)) {
				case 200:
					$('#flagLink_' + id).html(json.status.text);
				break;
				case 400:
					$('#flagLink_' + id).html(json.status.text);
				break;
				case 500:
				default:
					alert(json.status.text);
					if(!JS_AB.abtv.debug) window.location.reload();
				break;
			}
		},
		deleteComment: function(evt) {
			evt.preventDefault();
			if(confirm('Ben je zeker?')) {
				var id = $(this).attr('id').replace('delete_comment_', '');
				$.ajax({ url: '/ajax.php?module=abtv&action=delete_comment', 
						type: 'post', dataType: 'json', cache: false, 
						data: 'comment_id='+ id,
						success: function(json) { $('#comment-' + id).slideUp(); }
				});
			}
		},
		_eoo : true
	}
	
	JS_AB.abtv.player = 
	{
	    init: function() {
		$('#playerControls').bind('click', function(evt)
		{
		    evt.preventDefault();
		    $('#hiddenControls').toggle();
		});
	    }
	}
	
	JS_AB.abtv.rating = 
	{
		movieID: null,
		yourRatingWidth: 0,

		init: function()
		{
			// Store original text (e.g. 'your rating')
			var originalText = $('#abtvRating .ratingTextYours span').html();

			$('#abtvRating .ratingYours .rateInt').each(function(index) {

				// Store rating text (e.g. 'Good')
				var ratingText = $(this).html();

				$(this).click(function(evt)
				{
					// Prevent default action
					evt.preventDefault();

					// Change stars to reflect vote
					switch(index)
					{
						case 0:
							$(this).parent().find('#abtvRating .ratingOverlay').show().css('width', '13px');
							JS_AB.abtv.rating.yourRatingWidth = 13;
						break;
						
						case 1:
							$(this).parent().find('#abtvRating .ratingOverlay').show().css('width', '25px');
							JS_AB.abtv.rating.yourRatingWidth = 25;
						break;
						
						case 2:
							$(this).parent().find('#abtvRating .ratingOverlay').show().css('width', '37px');
							JS_AB.abtv.rating.yourRatingWidth = 37;
						break;
						
						case 3:
							$(this).parent().find('#abtvRating .ratingOverlay').show().css('width', '48px');
							JS_AB.abtv.rating.yourRatingWidth = 48;
						break;
						
						case 4:
							$(this).parent().find('#abtvRating .ratingOverlay').show().css('width', '61px');
							JS_AB.abtv.rating.yourRatingWidth = 61;
						break;
					}

					// handle ajax call
					JS_AB.abtv.rating.initSendRating(index + 1);

				});

				// Show rating text when hovering over one of the rating stars
				$(this).hover(function(evt)
				{
					JS_AB.abtv.rating.yourRatingWidth = $(this).parent().find('#abtvRating .ratingOverlay').width();
					$(this).parent().find('#abtvRating .ratingOverlay').hide();
					$(this).parent().next('#abtvRating .ratingTextYours').find('span').html(ratingText);
				}, function()
				{
					$(this).parent().find('#abtvRating .ratingOverlay').show().width(JS_AB.abtv.rating.yourRatingWidth);
					$(this).parent().next('#abtvRating .ratingTextYours').find('span').html(originalText);
				});
			});
		},

		initSendRating : function(rating)
		{
			JS_AB.abtv.rating.movieID = movieID;

			JS_AB.abtv.rating.doSendRating({'rating': rating, 'movie_id': JS_AB.abtv.rating.movieID});
		},

		doSendRating : function(postData) {
			$.ajax({
				url: '/ajax.php?module=abtv&action=send_rating',
				type: 'post',
				dataType: 'json',
				cache: false,
				data: postData,
				success: function(json) {
					JS_AB.abtv.rating.doneSendRating(json);
					//JS_AB.concerts.crowdHandler._doneToggleMe(json);
				},
				error: function(xhr,err,e) {alert(err + ' ' + e, 'Critical Error');}
			});
		},

		doneSendRating: function(json) {
			$('#abtvRating .ratingTextYours span').html(json.content.successMessage);

			// This updates the "main" rating, which is hidden in the .tpl until further notice
			var width = Math.floor(json.content.rating) * 12 + 1;
			$('#abtvRating .ratingOverlay').width(width);
			$('#abtvRating .ratingText span').html(Math.floor(json.content.count) + ' ' + json.content.countText);
		},

		_eoo: true
	}
	
	JS_AB.abtv.counter = 
	{
		days: undefined,	
		hours: undefined,	
		minutes: undefined,		
		seconds: undefined,	
		interval: undefined,
		
		init: function()
		{
			// get values
			JS_AB.abtv.counter.days = parseInt($('#days', '#counter').html(), 10);	
			JS_AB.abtv.counter.hours = parseInt($('#hours', '#counter').html(), 10);	
			JS_AB.abtv.counter.minutes = parseInt($('#minutes', '#counter').html(), 10);	
			JS_AB.abtv.counter.seconds = parseInt($('#seconds', '#counter').html(), 10);
			
			// start counting if there is a timediffernce!
			if(!
				(JS_AB.abtv.counter.seconds == 0 &&
				JS_AB.abtv.counter.minutes == 0 &&
				JS_AB.abtv.counter.hours == 0 &&
				JS_AB.abtv.counter.days == 0))
			{
				JS_AB.abtv.counter.interval = setInterval(JS_AB.abtv.counter.count, 1000);
			}
		},
		
		count: function()
		{
			// decrease seconds
			JS_AB.abtv.counter.seconds--;
			
			// should we add the 'nearEnd' class?
			if(JS_AB.abtv.counter.days == 0 && JS_AB.abtv.counter.hours == 0 && JS_AB.abtv.counter.minutes == 0 && JS_AB.abtv.counter.seconds <= 1)
			{
				if(!$('#seconds', '#counter').hasClass('nearEnd'))
				{
					// add class
					$('#seconds', '#counter').addClass('nearEnd');
				}
			}
			
			// reached seconds limit?
			if(JS_AB.abtv.counter.seconds == -1)
			{
				// reset seconds
				JS_AB.abtv.counter.seconds = 59;
				
				// decrease minutes
				JS_AB.abtv.counter.minutes--;
				
				// should we add the 'nearEnd' class?
				if(JS_AB.abtv.counter.days == 0 && JS_AB.abtv.counter.hours == 0 && JS_AB.abtv.counter.minutes <= 1)
				{
					if(!$('#minutes', '#counter').hasClass('nearEnd'))
					{
						// add class
						$('#minutes', '#counter').addClass('nearEnd');
					}
				}
				
				// reached minutes limit?
				if(JS_AB.abtv.counter.minutes == -1)
				{
					// reset minutes
					JS_AB.abtv.counter.minutes = 59;
					
					// decrease hours
					JS_AB.abtv.counter.hours--;
					
					// should we add the 'nearEnd' class?
					if(JS_AB.abtv.counter.days == 0 && JS_AB.abtv.counter.hours <= 1)
					{
						if(!$('#hours', '#counter').hasClass('nearEnd'))
						{
							// add class
							$('#hours', '#counter').addClass('nearEnd');
						}
					}
					
					// reached hours limit?
					if(JS_AB.abtv.counter.hours == -1)
					{
						// reset hours
						JS_AB.abtv.counter.hours = 23;
						
						// decrease days
						JS_AB.abtv.counter.days--;
						
						// should we add the 'nearEnd' class?
						if(JS_AB.abtv.counter.days <= 1)
						{
							if(!$('#days', '#counter').hasClass('nearEnd'))
							{
								// add class
								$('#days', '#counter').addClass('nearEnd');
							}
						}
					}
				}
				
			}
			
			// set values with leading 0 if needed
			$('#days', '#counter').html(JS_AB.abtv.counter.days < 10 ? '0' + JS_AB.abtv.counter.days : JS_AB.abtv.counter.days);
			$('#hours', '#counter').html(JS_AB.abtv.counter.hours < 10 ? '0' + JS_AB.abtv.counter.hours : JS_AB.abtv.counter.hours);
			$('#minutes', '#counter').html(JS_AB.abtv.counter.minutes < 10 ? '0' + JS_AB.abtv.counter.minutes : JS_AB.abtv.counter.minutes);
			$('#seconds', '#counter').html(JS_AB.abtv.counter.seconds < 10 ? '0' + JS_AB.abtv.counter.seconds : JS_AB.abtv.counter.seconds);
			
			if(
				JS_AB.abtv.counter.seconds == 0 &&
				JS_AB.abtv.counter.minutes == 0 &&
				JS_AB.abtv.counter.hours == 0 &&
				JS_AB.abtv.counter.days == 0)
			{
				clearInterval(JS_AB.abtv.counter.interval);
			}
			
		},

			
		// end
		eoo: true
	}
	
	$(document).ready(function() { JS_AB.abtv.init(); });
})(jQuery)
