(function($){
	var $videos = null;
	var $videosAll = null;
	var $albums = null;
	var $comments = null;
	var $xml = null;
	
	var $options = {
		'videosPerPage': 8,
		'channelPrefix': $config.prefix+' - '
	};
	
	var $filters = {
		'tag': null,
		'channel': null,
		'page': 1,
		'video': null
	};

 	$.fn.extend({
 		videos: function(options) {
			var $this = this;
			
			$options = $.extend($options, options);
			
			/**
			* getAlbums() will call getTags() once the albums are loaded.
			* getTags() will call getVideos() once the tags are loaded.
			* getVideos() will call embedVideo() once the videos are loaded.
			* They all depend on each other, so sequencing is needed here.
			*/
			$this.getAlbums();
			return $this;
    	},
		
		embedVideo: function() {
			var $this = this;
			$('#comments').remove();
			var $videoId = 'video-player';
			
			if($filters.video == null) {
				
				// Loop through all videos
				$.each($videosAll, function(i, item) {
					if(item['album_title'].indexOf($config.prefix + " - ") == 0 && jQuery.inArray('frontpage', item['tags']) > -1 && $filters.channel == null ) {
						$filters.video = item['photo_id'];
						return false;
					}
				});
				
				// Loop through $videos containing only this items for current page
				if($filters.video == null){
					$.each($videos.photos, function(i, item) {
						if(item['album_title'].indexOf($config.prefix + " - ") == 0) {
							$filters.video = item['photo_id'];
							return false;
						}
					});
				}
			}
			var $container = $($videoId).length > 0 ? $videoId : 'player-container';
			
			var params = { allowScriptAccess: "always", wmode: "transparent", allowfullscreen: "true" };
			var atts = { id: $container };
			var flashvars = { autoplay: '1', show_tray: 0, photo_id: $filters.video, showLogo: false};

			if($filters.video != null) {
				swfobject.embedSWF($config.url+'/'+$config.swf, "player-container", "709", "399", "8", null, flashvars, params, atts);
				$(window).scrollTop(0);
				return $this.showVideoDetails();
			} else {
				return $this;
			}
		},
		
		showVideoDetails: function() {
			var $this = this;
			var video = null;
            for(var i=0; i < $videosAll.length; i++) {
				if($videosAll[i].photo_id == $filters.video) {
					video = $videosAll[i];
				}
            }

			var $ratingStars = $('.rating .star');
			var $ratingForm = $('.rating form:first');

			$("input[name='return_url']", $ratingForm).val(window.location.href);
			$("input[name='photo_id']", $ratingForm).val($filters.video);
			
			$ratingForm.unbind('submit').submit(function() {
				var $this = $(this);
				$.post($this.attr('action'), $this.serializeArray(), function(data) {
					$('div.rating > span.stars').hide("fast", function() {
						$('div.rating > span.pink').after('<span class="thanks">Thanks for rating.</span>');
						window.setTimeout("$('div.rating span.thanks').hide('slow', function() { $('div.rating span.thanks').remove(); $('div.rating > span.stars').show('fast'); })", 1500);
					});
				});
				return false;
			});
			
			$ratingStars.each(function(i, star) {
				var	$ths = $(star);

				if(video != null) {
					var $rating = Math.round(5*video.photo_rating);
				} else {
					var $rating = Math.round(5*1);
				}

				$ths.unbind('click').click(function() {
					$ratingForm.submit();
					return false;
				});

				if(i+1 <= $rating) {
					$ths.addClass('on');
				}

				$ths.hover(
					function() {
						$('.rating').addClass('hover');
						var $val = $ths.attr('href').replace('#', '');
						$("input[name='rating']", $ratingForm).val($val);
						$ratingStars.each(function($i, $star) {
								if($i+1 <= $val) {
									$($star).addClass('hover');
								} else {
									$($star).removeClass('hover');
								}
							}
						);
					},
					function() {
						$('.rating').removeClass('hover');
						$ratingStars.removeClass('hover');
					}
				);
			});
			
			var tagsSpan = $('#player-details span.tags');
			tagsSpan.html('');
			
			if(video != null) {
				for(var i=0; i<video.tags.length; i++) {
					if(video.tags[i] != 'frontpage'){
						var link = $('<a href="">'+video.tags[i]+'</a>');
						link.attr('href', $this.getUrl('tag', {tag:video.tags[i]}));
						link.addClass('tag');
						tagsSpan.append(link);
					}
				}
			}

			if(video != null) {
				var commentsCount = $('#player-details span.comments');
				commentsCount.html($('<a class="comments pink" href="#">'+video.number_of_comments+'</a>'));
			}
			
			if(video != null) {
				var downloadLink = $('#player-details div.download a');
				downloadLink.attr('href', $config.url+video.standard_download.replace('/standard', '/video_original'));
			}
			return $this;
		},

		showComments: function() {
			var $this = this;
			$.getScript($config.url+$config.path+'/comments?object_id='+$filters.video, function() {
				$comments = visual;
				visual = null;
				var videos = $('#videos');
				$('#comments').remove();
				var comments = $('<div id="comments" class="right-col"><div><span class="pink">Comments:</span></div></div>');

				videos.before(comments);

				if($comments.comments.length > 0) {
					$comments.comments.reverse();
				}
				
				
				for(var i=0; i < $comments.comments.length; i++) {
					
					comments.append(
						$(
							'<div class="comment">' +
								'<p>' + $comments.comments[i].content_text + '</p>' +
								'<div class="details">' +
									'Posted on '+$comments.comments[i].pretty_date+' at '+$comments.comments[i].pretty_time+' by '+$comments.comments[i].name +
								'</div>' +
							'</div>'
						)
					);
				}

				$.get(
					'comments_form.html',
					{},
					function(data) {
						comments.append(data);
						$("input[name='return_url']").val(window.location.href);
						$("input[name='object_id']").val($filters.video);
						$('.auto-clear').focus(function() {
							var $this = $(this);
							if($this.val() == $this.attr('title')) {
								$this.addClass('activated');
								$this.val('');
							}
						}).blur(function() {
							var $this = $(this);
							if($this.val() == '') {
								$this.val($this.attr('title'));
								$this.removeClass('activated');
							}
						});
						$('#comments-form form').submit(function() {
							var $this = $(this);
							$.post($this.attr('action'), $this.serializeArray(), function(data) {
								$('#comments-form form').before('<p class="thanks">Thanks for commenting, your comment will show up here soon.</p>');
								//window.setTimeout("$('#comments-form p.thanks').hide('slow', function() { $('#comments-form p.thanks').remove(); })", 3000);
								$('#comments-form form').get(0).reset();
							});
							return false;
						});
						var $off = $('#player-details').offset();
						$(window).scrollTop($off.top - 30);
					}
				);
			});
			return $this;
		},
		
		getVideos: function(filters) {
			var $this = this;
			
			if(filters != undefined && typeof(filters) == 'object') {
				$filters = $.extend($filters, filters);
				
				if($filters.channel == 'Home') {
					$filters.channel = null;
				}
				
				$filters.page = parseInt($filters.page);
			}
			
			var $url = $config.url+$config.path+'/videos/?size=1000';
			
			if($filters.tag != undefined && $filters.tag != null) {
				$url = $url+$this.urlSeperator($url)+'tag='+$filters.tag;
			}
			
			if($filters.channel != undefined && $filters.channel != null) {
				var $album_id = $this.albumNameToId($options.channelPrefix+$filters.channel);
				
				if($album_id != false) {
					$url = $url+$this.urlSeperator($url)+'album_id='+$album_id;
				}
			}
			
			$.getScript($url, function() {
				$videos = visual;
				var $photos = new Array();
				var $photosAll = new Array();
				$.each($videos.photos, function(i, $video){
					if($video['album_title'].indexOf($config.prefix + " - ") == 0){
						if($filters.channel == null && $video['title'].indexOf("There are no") > -1){
							// dummy vid
						} else {
							$photos.push($video);
							$photosAll.push($video);	
						}
					}
				});
				
				$videosAll = $photosAll;
				$videos.photos = $photos.slice(($filters.page - 1) * $options.videosPerPage, $filters.page * $options.videosPerPage);
				$videos.total_count = $photos.length;
				$this.listVideos($videos);
				$this.embedVideo();
				$this.showAlbumInfo();
			});
			return $this;
		},

		showAlbumInfo: function() {
			var $this = this;
			var $channel = $filters.channel != null ? $filters.channel.toLowerCase() : 'home';
			var $contents = $($xml).find($config.prefix).find($channel);

			if($contents.length > 0) {
				$intro = $('#intro');
				$intro.html('');

				var $img = $('<img width="66" height="64" />')
				$img.attr('src', $('thumbnail', $contents).text());
				$intro.append($img);
				$img.wrap('<div class="img"></div>')
				$intro.append($('text', $contents).text());

				var $linkText = jQuery.trim($('linktext', $contents).text());

				if($linkText != '') {
					var $link = $('<a class="button"></a>');
					$link.append($linkText);
					$link.attr('href', $('link', $contents).text());
					$intro.append($link);
				}
				
			}
			return $this;
		},
		
		getAlbums: function() {
			var $this = this;

			$.get(
				'external/xml/en.xml',
				function(xml) {
					$xml = xml;
				}
			);
			
			$.getScript($config.url+$config.path+'/albums', function(){
				$albums = visual;
				visual = null;

				var $menu = $('#categories ul:first');

				$menu.append('<li><a class="channel selected" href="#channel/Home">Home</a></li>');
				$.each($albums.albums, function(i,item){
					if(item['title'].indexOf($config.prefix + " - ") == 0){
						var title = item['title'].replace($config.prefix + " - ","");
						$menu.append('<li><a class="channel" href="#channel/' + title + '">' + title + '</a></li>');				
					}
				});

				$this.showTags();
			});
			return $this;
		},

		showTags: function() {
			var $this = this;

			$.getScript($config.url+$config.path+'/videos', function(){
				var $tags = visual;
				visual = null;

				var tags = new Array();
				$.each($tags.photos, function(i,item){
					if(item['album_title'].indexOf($config.prefix + " - ") == 0){
						$.each(item.tags, function(ii,items){
							if($.inArray(items, tags) == -1) {
								tags.push(items);
							}
						});
					}
				});

				var $tagsMenu = $("#tags ul:first");

				$.each(tags, function(ii, tag) {
					if(tag != 'frontpage'){
						$tagsMenu.append('<li><a class="tag" href="#tag/' + tag + '">' + tag + '</a></li>');
					}
				});
				
				var $overflow = $("#tags ul:first li:gt(17)");
				if($overflow.size() > 0) {
					$overflow.addClass('overflow');
					$tagsMenu.append('<li class="notag"><a class="all" href="#tag">See all</a></li>');
				}
				
				$('a.all', $tagsMenu).live('click', function() {
					var $this = $(this);
					if($this.hasClass('on')) {
						$this.removeClass('on');
						$('.overflow', $tagsMenu).hide();
						$this.text('See all');
					} else {
						$this.addClass('on');
						$('.overflow', $tagsMenu).show();
						$this.text('Hide');
					}
				});				

				$this.setFiltersFromHash();
				$this.getVideos();
			});
			return $this;
    	},
		
		albumNameToId: function(albumName) {
			for(i=0; i<$albums.albums.length; i++) {
				if($albums.albums[i].title == albumName) {
					return $albums.albums[i].album_id;
				}
			}
			return false;
		},
		
		setFiltersFromHash: function () {
			var $hash = window.location.hash.substring(1);
			
			if($hash != undefined && $hash != null && $hash != '') {
				$hash = $hash.split('/');
				
				for($i = 0; $i < $hash.length; $i+=2) {
					switch($hash[$i]) {
						case 'channel':
							$filters.channel = $hash[$i + 1];
							$('a.channel').removeClass('selected');
							$('a.channel[href^="#'+$hash[$i]+'/'+$hash[$i + 1]+'"]').addClass('selected');
						break;
						case 'tag':
							$filters.tag = $hash[$i + 1];
							$('a.tag').removeClass('selected');
							$('a.tag[href^="#'+$hash[$i]+'/'+$hash[$i + 1]+'"]').addClass('selected');
						break;
						case 'video':
							$filters.video = $hash[$i + 1];
						break;
						case 'page':
							$filters.page = $hash[$i + 1];
						break;
					}
				}
			}
			
			return true;
		},
		
		urlSeperator: function(url) {
			return url.indexOf('?') == -1 ? '?' : '&';
		},
		
		getUrl: function(urlType, urlFilters) {
			urlFilters = $.extend(false, $filters, urlFilters);
			
			var includeFilters = {};
			
			switch(urlType) {
				case 'video':
					includeFilters = ['video', 'page', 'channel', 'tag'];
					break;
				default:
					includeFilters = ['page', 'channel', 'tag'];
					break;
			}
			
			var urlParts = new Array();
			
			for(var i=0; i < includeFilters.length; i++) {
				if(urlFilters[includeFilters[i]] != undefined && urlFilters[includeFilters[i]] != null) {
					urlParts.push(includeFilters[i]+'/'+urlFilters[includeFilters[i]]);
				}
			}
			
			return '#'+urlParts.join('/');
		},
		
		listVideos: function(videos) {
			var $this = this;
			var $items = $('#items');
			var $itemsInRow = 0;
			
			$items.html('');
			
			$.each(videos.photos, function(i,item){
				if(item['album_title'].indexOf($config.prefix + " - ") == 0){
					$items.append('<div class="item">' +
						'<a class="video" href="'+$this.getUrl('video', {video: item['photo_id']})+'">' +
						'<div class="thumb_image"><span class="video"><img src="' + $config.url + '/' + item['small_download'] + '"/></span><span class="button"></span></div>' + 
						'<p class="date">' + item['creation_date_ansi'].substr(0,10) + '</p>' + 
						'<p class="title">' + item['title'] + '</p>' +
						'<p class="category">' + item['album_title'].replace($config.prefix + " - ","") + '</p>' +
						'</a>' +
					'</div>');
					
					$itemsInRow++;
					
					if($itemsInRow == 4 || (i+1) == videos.photos.length) {
						$items.append('<div class="seperator"></div>');
						$itemsInRow = 0;
					}
				}
			});
			
			$this.showPagination();
			return $this;
		},
		
		showPagination: function(){
			var $this = this;
			var $pages = Math.ceil($videos.total_count/$options.videosPerPage);
			var $previous = $filters.page-1 > 0 ? $filters.page-1 : $filters.page;
			var $next = $filters.page+1 <= $pages ? $filters.page+1 : $filters.page;
			
			var $previousLink = $('<a class="previousBtn"></a>');
			$previousLink.addClass('page');
			$previousLink.attr('href', $this.getUrl('page', {page: $previous}));
			
			var $nextLink = $('<a class="nextBtn" href=""></a>');
			$nextLink.addClass('page');
			$nextLink.attr('href', $this.getUrl('page', {page: $next}));
			
			var $long = $("#pagination_long");
			var $short = $("#pagination_short");
			
			$short
				.html('')
				.append($previousLink)
				.append("Page " + $filters.page + " / " + $pages)
				.append($nextLink);
			
			$long
				.html('')
				.append($previousLink.clone());
				
			for(var $i=1; $i<= $pages; $i++) {
				var $link = $('<a class="page" href="">'+$i+'</a>');
				$link.attr('href', $this.getUrl('page', {page: $i}));
				
				if($filters.page == $i) {
					$link.addClass('selected');
				}
				
				$long.append($link);
			}
			
			$long.append($nextLink.clone());
			
			if($pages <= 1) {
				$long.hide();
				$('.page', $short).hide();
			} else {
				$long.show();
				$('.page', $short).show();
			}
			return $this;
		}
	});
})(jQuery);