var WIN, Rotator, pagination_offset = 0, pagination_total = 0, ratedText = "", currentResolution;

function getRatingText(percent) {
	return (percent > 80 ? 'Perfect' :
	       percent > 60 ? 'Good' :
	       percent > 40 ? 'Average' :
	       percent > 20 ? 'Mediocre' :
	                      'Lame') + ratedText;
}
function calculatePercent(el, mouseLeft) {
	var width = el.width(), left = el.position().left;
	var percent = ((mouseLeft - left) / (width) * 100);
	if (percent > 90) percent = 100;
	else if (percent > 80) percent = 90;
	else if (percent > 70) percent = 80;
	else if (percent > 60) percent = 70;
	else if (percent > 50) percent = 60;
	else if (percent > 40) percent = 50;
	else if (percent > 30) percent = 40;
	else if (percent > 20) percent = 30;
	else if (percent > 10) percent = 20;
	else if (percent > 0) percent = 10;
	return percent;
}

function showMoreLess(what, hiddenText, visibleText) {
	var link = $('#' + what + '_link');
	what = $('#' + what);
	if (what.css('visibility') == 'visible') {
		what.css('visibility', 'hidden').css('display', 'none');
		link.text(hiddenText);
	} else {
		what.css('visibility', 'visible').css('display', 'inline');
		link.text(visibleText);
	}
	return false;
}

function VideoList(list) {
	var dis = this;
	var resizeWaiting = false;

	var rows = list[0].className.match(/videos-([0-9]+)rows/);
	if (!rows || !rows[1]) rows = 4;
	else rows = parseInt(rows[1]);

	var max, min = list[0].className.match(/videos-([0-9]+)to([0-9]+)/);
	if (!min || !min[1]) {
		max = 15;
		min = 1;
	} else {
		max = parseInt(min[2]);
		min = parseInt(min[1]);
	}

	this.resetDelayed = function(nowait) {
		if (nowait && nowait == true) {
			resizeWaiting = window.setTimeout(dis.reset, 500);
		} else {
			window.clearTimeout(resizeWaiting);
			resizeWaiting = window.setTimeout(dis.reset, 400);
		}
		return dis;
	};

	this.reset = function() {
		var listId = list[0].className.match(/videos-id([A-Za-z0-9\-\_]+)/);
		list[0].className = list[0].className.replace(/fits[0-9 ]+/, '');
		var firstVisible = list.children('.videoblock:visible:first');
		var numPerRow = Math.floor(list.innerWidth() / (firstVisible.children(':first').innerWidth()+(currentResolution<=1024?3:8)));
		if (numPerRow < min) numPerRow = min;
		else if (numPerRow > max) numPerRow = max;
		var paginate = true;
		list[0].className = 'fits' + numPerRow +' '+ list[0].className.replace(/fits[0-9 ]+/, '');

		if (listId && listId[1]) {
			listId = listId[1];
			var fits = $.cookie('fits');
			if (!fits)
				fits = '';
			else
				fits += '&';
			fits = fits.replace(new RegExp('&?videos-id' + listId + '=[0-9]+'), '') + 'videos-id' + listId + '=' + numPerRow;
			$.cookie('fits', fits);
		}

		var isPaged = list.hasClass('videos-paged'), videosPage = 1, videosPages = 1;
		var videoblocks = list.children('.videoblock');
		if (isPaged) {
			videosPage = parseInt(list.data('page'));
			videosPages = Math.floor(videoblocks.length / (numPerRow * rows)); // FLOOR will return only the number of "full" pages
			if (isNaN(videosPage)) {
				videosPage = 1;
				var paginate_videos = function() {
					var match = parseInt(this.href.match(/[\-\+0-9]+$/));
					var pages = list.data('pages');
					var page = list.data('page');
					var newPage = page + match;

					if (newPage < 1)
						newPage = pages;
					else if (newPage > pages)
						newPage = 1;

					list.data('page', newPage);
					dis.reset();

					return false;
				};
				$(document.createElement('a')).addClass('video-paginate-prev').attr('href', '-1').click(paginate_videos).insertBefore(list.parent());
				$(document.createElement('a')).addClass('video-paginate-next').attr('href', '+1').click(paginate_videos).insertAfter(list.parent());
			}

			list.data('pages', videosPages);
			list.data('page', videosPage);
		}

		videoblocks.slice(0, (numPerRow * rows) * (videosPage - 1)).css('display', 'none');
		videoblocks.slice((numPerRow * rows) * (videosPage), videoblocks.length - 1).css('display', 'none');
		videoblocks.css('display', 'none');
		videoblocks.slice((numPerRow * rows) * (videosPage - 1), (numPerRow * rows) * (videosPage)).css('display', 'block');


		var curPerPage = $('.videos-pagination li.videoblock:visible');
		if (!curPerPage[0]) {
			curPerPage = list.find('li.videoblock:visible')
			paginate = false;
		}
		curPerPage = curPerPage.length;
		var hrefPage = document.location.href.match(/page=([0-9]+)/);
		    hrefPage = hrefPage && hrefPage[1] ? parseInt(hrefPage[1]) : 1;

		var paginationList = $('ul.pagination');
		var paginationItems = paginationList.children();

		if (paginate && paginationItems[0]) {
			var exampleLink = paginationList.find('a')[0].href.replace(/((&amp;)|\?|&)(page|offset)=[0-9]+/ig, '');
			var startQ = (exampleLink.indexOf('?') > -1 ? '&' : '?');

			paginationItems.remove();
		}

		var startFrom = 1, endAt = 10;
		var curPage = Math.floor(pagination_offset / curPerPage)+1;
		var pageCount = Math.ceil(pagination_total / curPerPage);

		if (paginate && paginationItems[0]) {
			var addLinks = '';
			if (pageCount <= endAt) {
				endAt = pageCount;
			} else if (curPage > 6) {
				addLinks += '<li><a href="' + exampleLink + startQ + 'offset=' + 0 /*+ '&page=' + 1*/ + '">First</a></li>';

				if (curPage > pageCount-4) {
					startFrom = pageCount - 9;
					endAt = pageCount;
				} else {
					startFrom = curPage - 5;
					endAt = curPage + 4;
				}
			}
			if (pagination_offset > 1) {
				addLinks += '<li><a href="' + exampleLink + startQ + 'offset=' + ((curPage-2)*curPerPage < 0 ? 0 : (curPage-2)*curPerPage) /*+ '&page=' + (curPage-1 < 1 ? 1 : curPage-1)*/ + '">&lt;&lt;</a></li>';
			}
			for (var i = startFrom; i <= endAt; i++) {
				if (i != curPage)
					addLinks += '<li><a href="' + exampleLink + startQ + 'offset=' + ((i-1)*curPerPage) /*+ '&page=' + (i)*/ + '">'+ i +'</a></li>';
				else
					addLinks += '<li class="active">'+ i +'</li>';
			}
			if (curPage < pageCount) {
				addLinks += '<li><a href="' + exampleLink + startQ + 'offset=' + ((curPage)*curPerPage) /*+ '&page=' + (curPage+1)*/ + '">&gt;&gt;</a></li>';
			}
			if (curPage < pageCount-4) {
				addLinks += '<li><a href="' + exampleLink + startQ + 'offset=' + (pageCount*curPerPage-curPerPage) /*+ '&page=' + (pageCount)*/ + '">Last</a></li>';
			}

			$(addLinks).appendTo(paginationList);
		}

		list.parents('div.block:first').find('.results-end-offset:first').text((pagination_offset + curPerPage) > pagination_total ? pagination_total : (pagination_offset + curPerPage));

		return dis;
	};

	list.addClass('_VideoList');
	list.data('VideoList', this);

	return this;
}

function handleResolution() {
	var winWidth = WIN.width();
	var resolutions = [1920, 1680, 1280, 1024, 780, 640];
	var lastSize = resolutions[0], lastDist = 9000;
	for (var i = 0; resolutions[i]; i++) {
		var newDist = Math.abs(resolutions[i] - winWidth);
		if (lastDist < newDist)
			break;
		lastDist = newDist;
		lastSize = resolutions[i];
	}
	var body = document.getElementsByTagName('body')[0];
	if (!currentResolution || !(new RegExp('resolution'+lastSize).test(body.className))) {
		currentResolution = lastSize;
		body.className = body.className.replace(/ *resolution[0-9]+/, '') + ' resolution'+lastSize;
		$.cookie('window_size', lastSize, { path: '/', expires: 30 });
	}
	$('._VideoList').each(function() { $(this).data('VideoList').resetDelayed(); });
}

function KEEEEEEZ() {
	WIN = $(window);

	handleResolution();
	WIN.resize(handleResolution);
	$('.videos').each(function() {
		new VideoList($(this)).resetDelayed(true);
	});


	Rotator = {
		el: false,
		duration: false,
		loader: new Image(),
		id: 1,
		title: '',
		max: 12,
		delay: 350,
		length: 0,

		prepare: function() {
			var el = $(this).children('img:first');
			if (el.data('timeout')) return false;
			el.data('oldsrc', el[0].src);
			el.data('newsrc', el[0].src.match(/^(.*[a-z]+)[0-9]*(\.[a-z]{2,4}.*)$/));
			Rotator.title = el[0].parentNode.title;
			el[0].alt = el[0].parentNode.title = '';
			Rotator.id = 1;
			Rotator.el = el;
			Rotator.duration = el.parent().find('.duration');
			Rotator.length = Rotator.duration.text().split(':');
			Rotator.length = parseInt(Rotator.length[0]) * 60 + parseInt(Rotator.length[1]);
			Rotator.swap();
		},

		stop: function() {
			try {
				window.clearTimeout(Rotator.el.data('timeout'));
				Rotator.el[0].alt = Rotator.el[0].parentNode.title = Rotator.title;
				Rotator.el[0].src = Rotator.el.data('oldsrc');
				Rotator.duration.text(Math.floor(Rotator.length/60) + ":" + (Rotator.length % 60 >= 10 ? '' : '0') + (Rotator.length % 60));
				Rotator.el.removeData('oldsrc');
				Rotator.el.removeData('newsrc');
				Rotator.el.removeData('timeout');
				Rotator.el = false;
				Rotator.duration = false;
			} catch(e) {}
		},

		swap: function() {
			try {
				if (Rotator.id > Rotator.max) Rotator.id = 1;
				var newsrc = Rotator.el.data('newsrc');
				Rotator.loader.onload = Rotator.change;
				Rotator.loader.src = newsrc[1] + Rotator.id + newsrc[2];
				if (Rotator.loader.loaded)
					Rotator.change();
			} catch(e) {}
		},

		change: function() {
			try {
				// Prevent simultaneous multi image loading
				if (parseInt(Rotator.loader.src.match(/^.*[a-z]+([0-9]*)\.[a-z]{2,4}.*$/)[1]) != Rotator.id) return false;
				Rotator.el[0].src = Rotator.loader.src;
				Rotator.duration.text(Math.floor(Rotator.length/Rotator.max*(Rotator.id-1)/60) + ":" + (Math.floor(Rotator.length/Rotator.max*(Rotator.id-1) % 60) >= 10 ? '' : '0') + Math.floor(Rotator.length/Rotator.max*(Rotator.id-1) % 60) + " / " + Math.floor(Rotator.length/60) + ":" + (Rotator.length % 60 >= 10 ? '' : '0') + (Rotator.length % 60));
				Rotator.id++;
				window.clearTimeout(Rotator.el.data('timeout'));
				Rotator.el.data('timeout', window.setTimeout(Rotator.swap, Rotator.delay));
			} catch(e) {}
		}
	};

	$('img.rotating').each(function() {
		var el = $(this);
		el.parent().mouseenter(Rotator.prepare);
		el.parent().mouseleave(Rotator.stop);
	});

	function toggleAdvancedSearch() {
		var el = $('#search_pane');
		if (el.css('display') != 'block') {
			el.css('opacity', 0).css('display', 'block').fadeTo(500, 1);
		} else {
			el.css('opacity', 1).fadeTo(500, 0, function(){$(this).css('display', 'none');});
		}
		return false;
	}
	$('#adv-search-close').click(toggleAdvancedSearch);
	$('#header .search-advanced a').click(toggleAdvancedSearch);

	$('#search_form').submit(function() {
		var field = $(this).find('input[name=search]');
		if (field[0].value == '' || field[0].value == "Search...")
			return false;
	});

	$('.featuredclick').click(function() {
		var to = this.href.match(/#[a-zA-Z0-9\-\_]+/); to = to[0];
		var el = $(this).parent();
		var next  = $(to);
		var first = el.parent().children(':first');
		var wrap  = el.parents('.featuredcats:first');
		var firstOff   = first.offset();
		var currentOff = el.offset();
		var nextOff    = next.offset();

		wrap.animate({
			scrollLeft: (nextOff.left-firstOff.left)
		}, 500);

		return false;
	});
}

function Rater(el, submit_url, video_id) {
	var dis = this, rating = 0;

	var first = el.children(':first');
	var next = el.next(':first');
	if (!next.hasClass('ratingtext'))
		next = false;

	this.rate = function(percent) {
		ratedText =  " <small>Saving...</small>";
		next.html(getRatingText(rating));
		rating = percent;
		$.post(submit_url, { id: video_id, value: (percent / 100 * 5) }, dis.rateCallback);
	};
	this.rateCallback = function(data) {
		el.addClass('voted');
		$.data(el[0], 'ratingWidth', rating);
		first.css('width', rating + '%');

		if (next) {
			if (data == "success")
				ratedText =  " <small>(Rated: " + (''+(rating / 100 * 5)).replace(/\.5/, '&frac12;') + ")</small>";
			else
				ratedText =  " <small>Error registering your vote.</small>";
			next.html(getRatingText(rating));
		}
	};

	$.data(el[0], 'ratingWidth', parseFloat(first.css('width')));

	el.mousemove(function(e) {
		window.clearTimeout(dis.ratingRemove);

		var percent = calculatePercent(el, e.pageX);
		first.css('width', percent + '%');

		if (next) {
			next.html(getRatingText(percent));
		}
	});
	el.mouseleave(function() {
		dis.ratingRemove = window.setTimeout(function() {
			var percent = $.data(el[0], 'ratingWidth');
			first.css('width', percent + '%');

			if (next) {
				next.html(getRatingText(parseFloat(percent)));
			}
		}, 500);
	});
	el.click(function(e) {
		window.clearTimeout(dis.ratingRemove);
		dis.rate(calculatePercent(el, e.pageX));

		return false;
	});

	return this;
}


$(document).ready(KEEEEEEZ);
