var Rotator, ratedText = "";
var minW = 974;
var widthWindow;



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.offset().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;
}

var relVidsShown = 0;
var relVidsCur = new Array();
var relVidsHook = new Array();
var relVidsTotal = new Array();

function setRelVidsShown(qty) {
	relVidsShown = qty;
	$.each(relVidsTotal, function(key,val) {
		if(val <= qty) {
			$(relVidsHook[key]).prev().hide();
			$(relVidsHook[key]).next().hide();
		}
		else if(val > qty) {
			$(relVidsHook[key]).prev().show();
			$(relVidsHook[key]).next().show();
		}

	});
}

function relVids_prev(e) {
	try {
		var key = e.currentTarget.href.match(/[0-9]+$/);
		var vids = $(relVidsHook[key]).children().filter('li').hide();
	} catch(err) { return false; }
	if( relVidsCur[key] == 0 ) {
		relVidsCur[key] = relVidsTotal[key];
	}
	if(relVidsCur[key]-relVidsShown > 0 ) {
		relVidsCur[key] -= relVidsShown;
	}
	else {
		relVidsCur[key] = 0;
	}
	for(var i=0;i<relVidsShown;i++) {
		if( relVidsCur[key]+i < relVidsTotal[key] ) {
			$(vids[relVidsCur[key]+i]).show();
		}
	}
	return false;
}

function relVids_next(e) {
	try {
		var key = e.currentTarget.href.match(/[0-9]+$/);
		var vids = $(relVidsHook[key]).children().filter('li').hide();
	} catch(err) { return false; }
	if(relVidsCur[key] < relVidsTotal[key]-relVidsShown ) {
		relVidsCur[key] += relVidsShown;
	}
	else {
		relVidsCur[key] = 0;
	}
	for(var i=0;i<relVidsShown;i++) {
		if( relVidsCur[key]+i < relVidsTotal[key] ) {
			$(vids[relVidsCur[key]+i]).show();
		}
	}
	return false;
}

function KEEEEEEZ() {

	$('#related_pornstar_videos_container').children().filter('div').each(function(key,val) {
		relVidsCur[key] = 0;
		relVidsHook[key] = $(val).children().filter('ul');
		relVidsTotal[key] = $(relVidsHook[key]).children().filter('li').length;
		$(val).prepend( $(document.createElement('a')).addClass('video-paginate-prev').attr('href', key).click(relVids_prev) );
		$(val).append(  $(document.createElement('a')).addClass('video-paginate-next').attr('href', key).click(relVids_next) );
	});

	Rotator = {
		el: false,
		duration: false,
		loader: new Image(),
		id: 1,
		title: '',
		max: 16,
		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]*)\d*(\.[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]*)(\d*)(\.[a-z]{2,4}.*)$/)[2]) != 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\-\_]+/)[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;
	});


	if ( $('div#rater_handle')[0] )
	{
		if( $.cookie('rated-'+$('input#rater_pornstar').val()) == null ) {
			$('div#rater_handle').draggable({
				axis: 'x',
				containment: 'parent',
				drag: function(event, ui) {
					$('div#rater_red').css('width', Math.round($(this).position().left / 159 * 100)+'%' );
					$('input#rater_rating').val( Math.round($(this).position().left / 159 * 100) );
					$('h3#rater_rate').html( $('input#rater_rating').val() );
				}
			});
			$('button#rater_submit').click( rater_click );
		}
	}

	if ($('#pornstar_dvds_btn')[0]) {
		$('#pornstar_dvds_btn').click(function(e) {
			if( $('#pornstar_dvds_iframe').attr('src') == "" )
				$('#pornstar_dvds_iframe').attr('src', $('#pornstar_dvds_iframe').attr('cachedsrc'));

			if( $('#pornstar_scenes').css('display') == 'block' )
			{
				$('#pornstar_scenes').hide();
				$('#pornstar_scenes_pagination').hide();
				$('#pornstar_dvds').show();
				$('#pornstar_dvds_btn').html('Watch Her: <strong>Scenes</strong>');
			}
			else if( $('#pornstar_dvds').css('display') == 'block' )
			{
				$('#pornstar_dvds').hide();
				$('#pornstar_scenes').show();
				$('#pornstar_scenes_pagination').show();
				$('#pornstar_dvds_btn').html('Purchase Her: <strong>DVDs</strong>');
			}
			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);
		$.cookie('rated-'+video_id,(percent / 100 * 5), {expires:1});
		$('button#rater_submit').unbind('click',rater_click);
	};
	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) {
		if( $.cookie('rated-'+video_id) == null )
		{
			window.clearTimeout(dis.ratingRemove);

			var percent = calculatePercent(el, e.pageX);
			first.css({ 'width': percent+'%',
						'background-position': '0px -44px',
						'cursor': 'pointer'
				});

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

			if (next) {
				next.html(getRatingText(parseFloat(percent)));
			}
		}, 500);
	});
	el.click(function(e) {
		if( $.cookie('rated-'+video_id) == null )
		{
			window.clearTimeout(dis.ratingRemove);
			dis.rate(calculatePercent(el, e.pageX));
		}
		return false;
	});

	return this;
}

/* Pornstar Rater */
function rater_click(e) {
	if( $.cookie('rated-'+$('input#rater_pornstar').val()) == null )
		$.post($('input#rater_url').val(),{ name: $('input#rater_pornstar').val(), value: $('input#rater_rating').val() }, function(e) {
			$.cookie('rated-'+$('input#rater_pornstar').val(),$('input#rater_rating').val(), {expires:1});
			$('button#rater_submit').unbind('click',rater_click);
			$('button#rater_submit').attr('disabled','disabled');
			$('p#rater_instructions').html('Thank you for your rating!');
			$('button#rater_submit').html('SUBMITED');
			$('div#rater_handle').hide();
		});
}

/* magic function */
$(document).ready(KEEEEEEZ);

/* ================= REDISTRIBUTION DEPENDING OF THE RESOLUTION ================= */

function calcWidth() {
		widthWindow = $(window).width();
		if( widthWindow <= minW ) {
			$('body').width(minW);
		}
		else if( widthWindow > minW ) {
			$('body').width('100%');
		}
	}

/* BROWSE PAGE */
function changeWidth() {
	if(widthWindow > 1300){
		thumbWrapper (16.6);
	} else if(widthWindow > 1100){
		thumbWrapper (19.9);
	} else {
		thumbWrapper (24.9);
	}
}
function thumbWrapper (width){
	$("div.video-thumbs").css("width" , width + "%");
	$("div.add-wrapper").css("width" , (width*2) + "%");
}

/* HOME PAGE UPPER PART */
function homeChangeWidth() {
	if(widthWindow > 1304){
		homeThumbWrapper (19.7);
	} else if(widthWindow > 1084){
		homeThumbWrapper (24.9);
	} else {
		homeThumbWrapper (32.9);
	}
}
function homeThumbWrapper (width){
	$("div.home-thumbs").css("width" , width + "%");
}

/* HOME PAGE BOTTOM PART */
function homeBodyChangeWidth() {
	if(widthWindow > 1280 ){
		homeBodyThumbWrapper (14.28);
	} else if(widthWindow > 1080){
		homeBodyThumbWrapper (16.5);
	} else {
		homeBodyThumbWrapper (19.9);
	}
}
function homeBodyThumbWrapper (width){
	$("div.home-body-thumbs").css("width" , width + "%");
}

/* HOME PAGE PORNSTAR PROFILE */
function homeBodyChangeWidthPs() {
	if(widthWindow > 1280 ){
		homeBodyThumbWrapperPs (12.5);
	} else if(widthWindow > 1080){
		homeBodyThumbWrapperPs (14.2);
	} else {
		homeBodyThumbWrapperPs (16.6);
	}
}
function homeBodyThumbWrapperPs (width){
	$("div.home-body-thumbs-ps").css("width" , width + "%");
}

/* VIDEO PAGE */
function videoWidth() {
	if(widthWindow > 1270){
		videoThumbWidth (16.5);
		setRelVidsShown(12);
	} else if(widthWindow > 1076) {
		videoThumbWidth (20);
		setRelVidsShown(10);
	} else {
		videoThumbWidth (25);
		setRelVidsShown(8);
	}
}
function videoThumbWidth(width){
	$("li.related-videos-th").css("width", width + "%");
}

/* PORNSTAR PAGE UPPER THUMB */
function pornStarUpChangeWidth() {
	if(widthWindow > 1200) {
		pornstarUpWidth (14.255);
	} else if(widthWindow > 1115) {
		pornstarUpWidth (16.3);
	} else {
		pornstarUpWidth (19.9);
	}
}

function pornstarUpWidth(width){
	$("li.porn-star-up-th").css("width", width + "%");
}

/* PORNSTAR PAGE BOTTOM BIG THUMBNAILS AND PORNSTARS BY LETTER */
function pornstarBigThumbs(){
	if(widthWindow > 1074 ) {
		pornstarBgThumbsWidth (19.9);
	} else {
		pornstarBgThumbsWidth (24.9);
	}
}
function pornstarBgThumbsWidth(width){
	$("li.pornstar-big-thmbs").css("width", width + "%");
}

/* RESIZE WRAPPERS */
function resizeWrapper(){
	 if(widthWindow > 1200){
		$("#outer").css("width" , 1240 + "px");
		$("#top-bar").css("width" , 1240 + "px");
		$("#header").css("width" , 1240 + "px");
	}  else if(widthWindow > minW ){
		$("#outer").css("width" , 95 + "%");
		$("#top-bar").css("width" , 95 + "%");
		$("#header").css("width" , 95 + "%");
	} else {
		$("#outer").css("width" , minW + "px");
		$("#top-bar").css("width" , minW + "px");
		$("#header").css("width" , minW + "px");
	}
}

/* CATEGORIES PAGE */
function categoriesChangeWidth() {
	if(widthWindow > 1800){
		categoriesWidth (19.9);
	} else if(widthWindow > 1264){
		categoriesWidth (19.9);
	} else if(widthWindow > 1189){
		categoriesWidth (19.9);
	} else if(widthWindow > 1016){
		categoriesWidth (24.9);
	} else {
		categoriesWidth (32.9);
	}
}
function categoriesWidth(width){
	if( $("li.thumbs-star").length >= 4 ) {
		$("li.thumbs-star").css("width", width + "%");
	}
	else {
		$("li.thumbs-star").css("width", "33%");
	}
}

/*  main-CATEGORIES PAGE */
function categoriesMainChangeWidth() {
	if(widthWindow > 1418){
		categoriesMainWidth (24.9);
	} else if(widthWindow > 1218){
		categoriesMainWidth (24.9);
	} else if(widthWindow > 1018){
		categoriesMainWidth (32.9);
	} else {
		categoriesMainWidth (49.9);
	}
}
function categoriesMainWidth(width){
	$("li.browse-categories").css("width", width + "%");
}

$(document).ready(function(){
	$(window).resize(calcWidth);						calcWidth();
	$(window).resize(resizeWrapper);					resizeWrapper();
	$(window).resize(changeWidth);						changeWidth();
	$(window).resize(videoWidth);						videoWidth();
	$(window).resize(homeChangeWidth);					homeChangeWidth();
	$(window).resize(homeBodyChangeWidth);				homeBodyChangeWidth();
	$(window).resize(categoriesChangeWidth);			categoriesChangeWidth();
	$(window).resize(categoriesMainChangeWidth);		categoriesMainChangeWidth();
	$(window).resize(homeBodyChangeWidthPs);			homeBodyChangeWidthPs();
	if( document.location.pathname.match(/\/pornstar/i) ) {
		$(window).resize(pornStarUpChangeWidth);		pornStarUpChangeWidth();
		$(window).resize(pornstarBigThumbs);			pornstarBigThumbs();
	}



	//Comments textarea
	$("textarea#comment-textarea").keyup(function(){
		commentsCount($(this));
	});
});

/*Download video funciton*/
	function startDownload(urlVideo)
	{
		var url=urlVideo;
		window.open(url,'Download');
	}

/*Avoid Cache of stats images*/
	function printStatsImages(siteId){
		$("body").append('<img src="http://ec2-204-236-204-43.compute-1.amazonaws.com/'+siteId+'" id="imgStat01" width="1" height="1"/>' +
								'<img src="http://ihstats.cloudapp.net/pv/default.ashx?sid='+siteId+'" id="imgStat02" width="1" height="1"/>');
	}


/* Comments */

var commentCurrentPage = 0;
var commentCurrentOrder = 0;

function addComment() {
	var objectId = $("input#video_id").val();
	if($("textarea#comment-textarea").val().length < 3 ) {
		alert("Please enter text");
	} else {
		$.post("http://"+document.domain+"/ajax/add_comment", { "object_id": objectId, "content": $("textarea#comment-textarea").val() }, function(result) {
			if( result ) {
				$("textarea#comment-textarea").val("");
				getComments(objectId, commentCurrentPage, commentCurrentOrder);
				$("div.count-character span").text(1000)
			} else {
				alert("Can't add comment");
			}
		},"json");
	}
}

function markComment(commentId) {
	var answer = confirm('Are you sure you want to flag this comment?');
	if (answer)	{
		$.post("http://"+document.domain+"/ajax/mark_comment", { "object_id": commentId }, function(result) {
			if( result ) {
				$("#comment_"+commentId).attr('class','flagged');
				$("#comment_"+commentId).html("");
			} else {
				alert("Can't mark as spam");
			}
		},"json");
	}
}
function markSelectedTab(tab) {
	$("a.tabs").removeClass("active");
	$("a."+tab).addClass("active");
}

function getComments(objectId, page, order) {
	var currentDate = new Date();
	$.get("http://"+document.domain+"/ajax/get_comments", { "object_id": objectId, "page": page, "order": order, "time": currentDate.getTime() }, function(result) {
		$("#comments_pane").html(result);
	},"json");
}

function showComments(objectId) {
	//markSelectedTab("comment-box");
	getComments(objectId, commentCurrentPage, commentCurrentOrder);
}

function showCommentsPage(objectId, inc) {
	getComments(objectId, commentCurrentPage+inc, commentCurrentOrder);
}

function showCommentsOrder(objectId, order) {
	getComments(objectId, commentCurrentPage, order);
}