///////////////////////////////////////////////////////////////////////////////////////////
// Javascript code to be included in the header sections of PlumperPass membership sites //
// Part of MAS(R) setup									 //
// (c) 2011 Mansion Productions LLC.							 //
//											 //
// Do not modify unless you really know what you're doing!				 //
// Errors in this script may cause plumperpass.com to go down (both tour & members areas //
///////////////////////////////////////////////////////////////////////////////////////////


//----------------------------------------
// Global state variables & configuration
//----------------------------------------

function plumperPassInitialState() {
	this.activePage    = 'home'; 		// home || scenes || models || scene || model
	this.gridMode      = 'list';		// grid || list
	this.favoritesMode = 'scenes';
	this.avc           = [];
	this.avMore	   = '';
	this.filterBySite  = '';
	this.sortBy	   = '';
	this.pageNr	   = null;
	this.homeSite      = 'ALL';
	this.modelScenes   = [];
	this.warningOpen   = false;
	this.popState      = false;
	this.pushState     = false;
	this.restoreState  = false;
};
var plumperPass = new plumperPassInitialState();
	
var plumperPassConfig = {
	isTour			: false,
	searchRef  		: 330,
	searchCategories 	: '2,3',
	scenesCategory		: 2,
	modelsCategory		: 3,
	scenesGridSection	: 345,
	modelsGridSection	: 360,
	favoritesScenesSection	: 385,
	favoritesModelsSection	: 386,
	jwplayerStreamer	: 'rtmp://streaming.plumperpass.com/stream/',
	pageTitlePrefix		: 'SENSATIONAL VIDEO.com Presents : Plumper Pass.com - ',
	uvarpass		: '',
	ratingScale		: 10,
	ajaxRateURL		: 'http://control.sensationalcash.com/ajax_rate.php',
	rotatingBackgroundTourHome: false,
	
	fullSiteURL : function(prefix) {
		switch (prefix) {
			case 'HSP': return 'HOTSEXYPLUMPERS.com';
			case 'BGB': return 'BBWsGONEBLACK.com';
			case 'BBJ': return 'BIGBABEBLOWJOBS.com';
			case 'BWD': return 'BBWDREAMS.com';
			case 'FTF': return 'FIRSTTIMEFATTIES.com';
			case 'PAP': return 'PLUMPERSATPLAY.com';
			default: return false;
		}	
	}
};

if (window.location.pathname.indexOf('/members')==-1) {
	plumperPassConfig.isTour = true;
	plumperPassConfig.searchRef		= 365;
	plumperPassConfig.scenesGridSection 	= 370;
	plumperPassConfig.modelsGridSection 	= 369;
	plumperPassConfig.pageTitlePrefix	= 'Plumper Pass - The Best In BBW, Plumper, Chubby & Fat Porn - ';
}

var plumperPassTour = {
	currentImage: 1,
	totalImages:  4
}

//--------------------------------------
// History.js Initialization & Bindings
// http://balupton.github.com/history.js
//--------------------------------------

window.onhashchange = function() {
	// Prevent page from scrolling when a #hashchange has occurred. Doesn't work in IE...
	if (window.location.hash == "" || window.location.hash == "#")  return false;
}; 


(function(window,undefined) {
 	// Prepare
 	var History = window.History; // Note: We are using a capital H instead of a lower h
 	var State = History.getState();
 	
	if (typeof(State.data.homeSite) != 'undefined') {
		// Restore Initial State (after REFRESH)
		plumperPass = State.data;
		plumperPass.pushState = false; 
		plumperPass.popState = false;
		plumperPass.restoreState = true; // Inform document.ready function to call restoreState() after page is loaded and inited
		// History.log('Refresh state ' + plumperPass.homeSite);
	} else {
		var b=plumperPass.backgroundImages;
		plumperPass = new plumperPassInitialState();
		plumperPass.backgroundImages=b;
		
		// Check if new search query string has been provided (i.e. scenes/models page used as search results)
		// query should be in the form: ?scenes|site|attribute, or ?scenes|attribute ; resp. ?models|site|attribute, or ?models|attribute
		try { var s = location.search.slice(1).split('&')[0].split('|'); } catch(err) { var s = [] }
		if ((s.length > 1) && ((s[0] == 'scenes') || (s[0] == 'models'))) {
			plumperPass.activePage = s[0];
			if (s.length >= 3) {
				plumperPass.filterBySite = s[1];
				plumperPass.avMore = s[2];
			} else {
				plumperPass.avMore = s[1];
			}
			plumperPass.restoreState = true;
		}
	}	
	
	// Bind to StateChange Event
	History.Adapter.bind(window,'statechange',function(){ // Note: We are using statechange instead of popstate
		var State = History.getState(); // Note: We are using History.getState() instead of event.state

		if (plumperPass.pushState) {
			// This is a PUSH event.
			// An AJAX called had happened (initiated by user)
			// We don't have to do anything except log the new state
			// History.log('New state ' + State.data.homeSite);
		} else {
			// This is a POP event
			// We have to restore the previous state
			if (typeof(State.data.homeSite) == 'undefined') {
				var b=plumperPass.backgroundImages;
				plumperPass = new plumperPassInitialState();
				plumperPass.backgroundImages=b;
			} else {
				plumperPass = State.data;
				plumperPass.pushState = false; 
				plumperPass.popState = false;
				plumperPass.restoreState = false;
			}
			// History.log('Prev state ' + plumperPass.homeSite);
			restoreState();
		}
		plumperPass.pushState = false;
	});
})(window);


function restoreState() {
	plumperPass.popState = true; // to inform JLoadContent that we are restoring old state
	if (plumperPass.activePage == 'home') {
		$('#siteButton' + (plumperPass.homeSite?plumperPass.homeSite:'ALL')).click();

	} else if (plumperPass.activePage == 'scenes' || plumperPass.activePage == 'models') {
		updateGridContent();
	} else if (plumperPass.activePage == 'favorites') {
		$('#'+plumperPass.favoritesMode+'button').click();
	}

	plumperPass.popState = false;
	plumperPass.restoreState = false;
};



//-----------------------------------
// Various jquery plugins and inits
//-----------------------------------

function rotator_initCallback(carousel) {
	$('span.setas-right').bind('click', function() {
		carousel.next();
		return false;
	});
	$('span.setas-left').bind('click', function() {
		carousel.prev();
		return false;
	});
};


// Rotating images on tour home
function setBorder(i, on) {
	if (on) { $('.lists-scenesA > li:nth-child('+i+') > .thumb').css('border','2px solid #46AADF'); }
	else 	{ $('.lists-scenesA > li:nth-child('+i+') > .thumb').css('border',''); }
}
function displayNextImage() {
	if (plumperPass.warningOpen) return; // hold on while the warning splash is open
	$('#wallpaper' + plumperPassTour.currentImage).fadeOut();
	setBorder(plumperPassTour.currentImage, false);

	plumperPassTour.currentImage++;
	if (plumperPassTour.currentImage > plumperPassTour.totalImages) plumperPassTour.currentImage = 1;

	setBorder(plumperPassTour.currentImage, true);
	$('#wallpaper' + plumperPassTour.currentImage).fadeIn();
}


function initWallpaper(givenNumber) {
	
	// Mask for modal dialogs as rating and add-to-fav
	$('body').prepend('<div id="modalMask"></div>');
	
	/* ------------------------------------------------------------------------------- 
	// -- disabled, as requested in ticket #9071 item #0 --

	if (plumperPass.activePage == 'home' && plumperPassConfig.isTour) {
		if (plumperPassConfig.rotatingBackgroundTourHome) {
			// Rotating background images for tour home page
			$('#wallpaper' + plumperPassTour.currentImage).show();
			setBorder(plumperPassTour.currentImage, true);
			setInterval('displayNextImage()', 5000);
			return;
		} else {
			// just the blue border on hover
			$('.lists-scenesA > li > div.thumb').hover( 
				function () { $(this).css('border','2px solid #46AADF'); },
				function () { $(this).css('border','2px solid #1b1b1b'); }
			);
		}
	} 
	
	// Set big background image
	if (typeof(givenNumber)=='undefined' || typeof(plumperPass.backgroundImages[givenNumber-1])=='undefined') {
		bgImageTotal = plumperPass.backgroundImages.length;
		givenNumber = Math.round(Math.random()*(bgImageTotal-1))+1;
	}
	imgPath = plumperPass.backgroundImages[givenNumber-1]; //  ('images/big-background/'+randomNumber+'.jpg');
	// Background-scaling patch for browsers that don't support it (supported in IE9+, Firefox 4+, Opera, Chrome, and Safari 5+)
	if ($.support.cssProperty('background-size')) { 
		$('body').css('background-image', ('url("'+imgPath+'")'));
	} else {
		var wallpaperImg = '<div id="wallpaper"><img src="'+imgPath+'"></div>';
		$('body').prepend(wallpaperImg);
	}

	------------------------------------------------------------------------------- */
}


function setCookie(c_name,value,exdays) {
	var exdate=new Date();
	exdate.setDate(exdate.getDate() + exdays);
	var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
	document.cookie=c_name + "=" + c_value;
}

function getCookie(c_name) {
	var i,x,y,ARRcookies=document.cookie.split(";");
	for (i=0;i<ARRcookies.length;i++) {
		x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
		y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
		x=x.replace(/^\s+|\s+$/g,"");
		if (x==c_name) {
			return unescape(y);
		}
	}
}


function showWarningPage() {
	if (getCookie("ppWarningPassed") == 1) return;

	$('#splashEnter').click(function() {
		setCookie('ppWarningPassed', 1);
		$('.splashPage').hide();
		$('#modalMask').hide();
		plumperPass.warningOpen = false;
		return false;
	});

	$('#modalMask').click(function(){return false;}).show();
	$('.splashPage').show();
	plumperPass.warningOpen = true;
}


function initGrids() {
	if (plumperPass.activePage=='models') {
		if (plumperPass.sortBy==6 && plumperPass.pageNr==1) {
			$('#firstSmall').remove();
		} else {
			$('#firstBig').remove();
		}
	}
	$('#'+plumperPass.gridMode+'Button').click();
}


function initGridButtons() {
	$("#gridButton").click(function () { 
		var gridContent = $("#grid-content");
		var listContent = $("#list-content");
		$(this).addClass('select'); 
		$("#listButton").removeClass('select');
		plumperPass.gridMode = 'grid';
		listContent.hide();
		gridContent.show();
		return false;
	});
	$("#listButton").click(function () { 
		var gridContent = $("#grid-content");
		var listContent = $("#list-content");
		$(this).addClass('select'); 
		$("#gridButton").removeClass('select');
		plumperPass.gridMode = 'list';
		gridContent.hide();
		listContent.show();
		return false;
	});
	$('#sortBy a').click(function () {
		var thisButton = $(this);
		if (!thisButton.hasClass('select')) {
			$('#sortBy a').removeClass('select');
			thisButton.addClass('select');
			updateGridContent();
		}
		return false;
	});
	$('#currentSite').click(function () {
		$('#filterBySite').slideToggle();
	});
	$('#filterBySite a').click(function () {
		var thisButton = $(this);
		if (!thisButton.hasClass('select')) {
			$('#filterBySite a').removeClass('select');
			thisButton.addClass('select');
			$('#currentSite').html(thisButton.html());
			$('#filterBySite').hide();
			updateGridContent();
		} else {
			$('#filterBySite').hide();
		}
		return false;
	});
}


function initFavoritesModeButtons() {
	$('#modelsButton').click(function () { 
		$(this).addClass('select'); 
		$('#scenesButton').removeClass('select');
		plumperPass.favoritesMode = 'models';
		plumperPass.pageNr = 1;
		updateFavoritesContent();
		return false;
	});
	$('#scenesButton').click(function () { 
		$(this).addClass('select'); 
		$("#modelsButton").removeClass('select');
		plumperPass.favoritesMode = 'scenes';
		plumperPass.pageNr = 1;
		updateFavoritesContent();
		return false;
	});
	$('#'+plumperPass.favoritesMode+'Button').click();
}


function initTabs() {
	var tabFirst = 0;
	var tabContainers = $('div.tabs > div');
	tabContainers.hide().filter(':eq('+tabFirst+')').show();

	$('div.tabs ul.tabNavigation a').filter(':not(.disabled)').click(function () {
		tabContainers.hide();
		tabContainers.filter(this.hash).show();
		$('div.tabs ul.tabNavigation a').removeClass('selected');
		$(this).addClass('selected');
		return false;
	}); //.filter(':first').click();
	$('div.tabs ul.tabNavigation a').filter(':eq('+tabFirst+')').click();
}


function initSitesButtons() {
	$('.align-sites a').each(function(){
				var t = $(this);
				t.attr('id', 'siteButton'+t.html());
				t.attr('rel', t.attr('href'));
				t.attr('href', 'javascript:;');
			}).click(function () {
				var t = $(this);
				var thisButton = t.attr('id').slice(10);
				if (true || thisButton != plumperPass.homeSite) {
					$('.align-sites a').removeClass('select');
					t.addClass('select');
					plumperPass.homeSite = thisButton;
					JLoadContent(t.attr('rel'), {container:'latestScenesContent', pageTitle:plumperPass.homeSite+' Latest Scenes'}, '?home&site='+plumperPass.homeSite);
				}
				return false;
			});
}


function initSceneButtons() {
	// videoPlayer Lights On/Off button
	$(".videoplayerButton a.off").click(function () { 
		$(this).toggleClass('on');
		if ($(this).hasClass('on'))
			$(".videoplayerOverlay").fadeIn(1000); 
		else
			$(".videoplayerOverlay").fadeOut(1000); 
		return false;
	});

	// DOWNLOAD dropdown menu
	$("#menu li a[href='#']").click(function () {
		$('#menu li').toggleClass('open');
		return false;
	});
	$("#menu li a[href!='#']").click(function(event) { 
		event.stopPropagation(); 
	});
	$('body').click(function (e) {
		if (!e) var e = window.event;
		if (e.target.tagName!="A" && e.target.tagName!="a") {
			var downloadMenu = $('#menu li');
			if (downloadMenu.hasClass('open')) {
				downloadMenu.removeClass('open');
				return false;
			}
		}
	});


	// Play Buttons
	// * Empty buttons (non-existing formats - remove;
	// * Buttons with a href="http:..." (e.g. Join page - ignore
	//   other buttons (e.g. path to video/trailer - load href into player
	$('.playButton[href=""]').remove();
	$(".playButton").filter(':not([href^="http"])').click(function (event, a) { 
		$(".playButton").removeClass('select');
		var t = $(this);
		t.addClass('select'); 
		jwplayerLoad(t.attr('href'), t.attr('width'), t.attr('height'), (typeof(a)=='undefined' || a!='init')?'play':'' );
		return false;
	}).filter(':visible:first').trigger('click','init');
	
	
	// Player Seek Buttons
	$(".playerSeek").click(function () { 
		jwplayerSeek($(this).attr('href') * 60);
		return false;
	});
	if ($(".playerSeek").length==0) $('.vidclips').hide();
	
	
	if (plumperPassConfig.isTour) {
		// there are no tabs buttons on tour, so just fix the position of the lights button and return

		$('.videoplayerButton').css('top', 670);
		return;
	}

	// -------------------------------------------

	// Scenes/Photos/Comments tab
	$("#videosButton").click(function () { 
		$(this).addClass('selected'); 
		$("#commentsButton,#photosButton").removeClass('selected');
		// $("#commentsTab").hide();
		$("#photosTab").hide();
		$("#videosTab").show();
		return false;
	});
	$("#photosButton").click(function () { 
		$(this).addClass('selected'); 
		$("#commentsButton,#videosButton").removeClass('selected');
		$("#commentsTab").hide();
		$("#videosTab").hide();
		$("#photosTab").show();
		
		// Dynamically load the photo gallery only when Photos tab is clicked for the first time
		if (!$(this).attr('loaded')) {
			$('#photosTab').css('min-height',$('#videosTab').height()).prepend(getPreloader(2));
			var w = $('#photosTab').width();
  			if (w<200) w=1050;
  			$('#jload_preloader').css('left', w - $('#jload_preloader').width() - 40).css('top', 46);
			
			var link = window.location.href;
			var fragment = '^pictures';
			link = link.replace('&s=',fragment+'&s=');
			$('#photosTab').load(link, function(){ 
				$('#photosButton').attr('loaded','true');
				setColorBox('photosTab', true, false);		// init colorbox for hires images
				// changeLinks('photosTab','^pictures');	// change pagenumber links in photos fragment to load pages using Ajax
			});
		}
		
		return false;
	});
	$("#commentsButton").click(function () { 
		$(this).addClass('selected'); 
		$("#videosButton,#photosButton").removeClass('selected');
		$("#videosTab,#photosTab").hide();
		$("#commentsTab").show();
		return false;
	});	
	$("#videosButton").click();

	
	// Close Description button
	$(".close").each(function(){
		var t = $(this);
		t.attr('rel', t.attr('href'));
		t.attr('href', 'javascript:;');
	}).click(function () { 
		$($(this).attr('rel')).hide();
		return false;
	});
}


function initModelButtons() {
	// Scenes/Comments tab
	$("#commentsButton").click(function () { 
		$(this).addClass('selected'); 
		$("#scenesButton").removeClass('selected');
		$("#scenesTab").hide();
		$("#commentsTab").show();
		return false;
	});	
	$("#scenesButton").click(function () { 
		$(this).addClass('selected'); 
		$("#commentsButton").removeClass('selected');
		// $("#commentsTab").hide();
		$("#scenesTab").show();
		return false;
	});
	$("#scenesButton").click();
}


function initFavoritesButtons(scope) {
	if (plumperPassConfig.isTour) return false; // No favorites on tour
	
	if (typeof(scope)!='undefined') var C = '#' + scope + ' '; else var C = '';
	$(C+'a.addfav').each(function() {
		var link = $(this).attr("href");
		var thisButton = $(this);
		var tm = new Date().getTime();
		link += '&display=no&timecache='+tm;
		if (plumperPass.activePage == 'favorites') {
			// Delete from favorites
			thisButton.attr("href", "javascript:;").click(function() {
				$.ajax({ url: link, context: document.body, success: function() {
					updateFavoritesContent();
				}});
				return false;
			});
		} else {
			// Add to favorites
			thisButton.attr("href", "javascript:;").click(function() {
				thisButton.addClass('selected');
				var offset = thisButton.offset(); 
				offset.left += 5;
				offset.top -= thisButton.height() + $('#addFavBox').height();
				$('#modalMask').click(function(){return false;}).show();
				$.ajax({ url: link, context: document.body, success: function() {
					var subject = (plumperPass.activePage=='home' || plumperPass.activePage=='scenes' || plumperPass.activePage=='scene')?'Scene':'Model';
					subject = subject + ' added to your favorites.';
					$('#addFavBox').html(subject).click(function(){$('#modalMask').hide(); $(this).hide(); thisButton.removeClass('selected');}).css('left','-50px').css('top',offset.top-400).css('opacity',0).show();
					$('#addFavBox').animate({'left':offset.left, 'top':offset.top, 'opacity':1}, 700);
					$('#modalMask').click(function(){$(this).hide(); $('#addFavBox').hide(); thisButton.removeClass('selected');});
				}});
				return false;
			});
		}
	});	
}


function initRateButtons(scope) {
	if (typeof(scope)!='undefined') var C = '#' + scope + ' '; else var C = '';
	$(C+'a.rate').each(function() {
		var thisButton = $(this);
		thisButton.attr("href", "javascript:;").click(function() {
			thisButton.addClass('selected');
			var offset = thisButton.offset(); 
			offset.left -= 50;
			offset.top -= thisButton.height() + $('#rateBox').height();
			$('#modalMask').click(function(){return false;}).show();
			
			if (plumperPassConfig.isTour) {
				var rateHtml = 'Must be a member to vote.';
			} else {
				var lid = '0';
				var rateHtml = '<ul class="star-rating">';
				rateHtml += '<li class="current-rating" style="width:' + Math.round(rate_class.currentWidth) + 'px"></li>';
				for (var i=1; i<=plumperPassConfig.ratingScale; i++) {
					rateHtml += '<li><a href="javascript:;" class="ratestar star' + i + '" onclick="return rate_class.rate(' + i + ')"></a></li>';
				}
				rateHtml += '</ul>';
				rateHtml += '<div class="your-rating" style="display:none"><span>new rating</span><br /><strong></strong></div>';
			}

			$('#rateBox').html(rateHtml).css('left','-200px').css('top',offset.top-400).show();
			$('#rateBox').animate({'left':offset.left, 'top':offset.top}, 700);
			$('#modalMask').click(function(){$(this).hide(); $('#rateBox').hide(); thisButton.removeClass('selected');});
			return false;
		});
	});	
}


function initSearch() {
	// Search-autosuggest
	if (plumperPassConfig.isTour) {
		$('#search').click(function() {	
			$('div.searchDetails').toggle(); 
		});
	} else {
		$('#autosug').click(function() {	
			$('div.searchDetails').show(); 
			$('body').bind('click.closesearch', function(e) {
				try {
					if ($(e.target).closest('div.search').length==0)  {	// e.g. click outside of div.search
						$('div.searchDetails').hide(); 
						$('body').unbind('click.closesearch');
					}
				} catch(ex){};
			});
		});
	}
	$('#autosug').masSearchAutoSuggest({'categories':plumperPassConfig.searchCategories, 'categoriesInputName':'categories', 'masurl':'http://control.sensationalcash.com/', 'ref':plumperPassConfig.searchRef});
	$('#headersearchform').submit(function() {
		var selected = $('#autosug div a[class$="_selected"]').filter(':first').attr('href');
		if (typeof(selected)=='undefined') selected = $('#autosug div a').filter(':first').attr('href');
		if (typeof(selected)!='undefined') {
			// location.href(selected);
			eval("self.location='"+selected+"'");
		}
		return false;
	});

	// Model Directory Slider
	$('.modeldirectory a').click(function () {
		$(this).toggleClass('select');
		$("#slider_panel").slideToggle("slow");
		if ($(this).hasClass('select') && !$(this).attr('loaded')) {
			$('#slider_modellists').load($(this).attr('rel'), function(){ 
				$('.modeldirectory a').attr('loaded','true');
				$('#slider_modellists h4 a').click(function () {
					$('#slider_modellists div.page').hide();
					$($(this).attr('rel')).show();
					return false;
				});
				$('#slider_modellists li a').hover( 
					function () { 
						var thisLink = $(this);
						var offset = thisLink.position(); 
						offset.left += -10;
						offset.top += 26;
						// $('#modelslistFaceimage').html('<img src="'+thisLink.attr('rel')+'">').show().animate({'left':offset.left, 'top':offset.top}, 700);
						$('#modelslistFaceimage').html('<img src="'+thisLink.attr('rel')+'">').css('left',offset.left).css('top',offset.top).show();
					},
					function () {
						$('#modelslistFaceimage').hide(); 
					}
				);				
			});
		}
  	});
}


function initArrowExpand() {
	$('div.arrowexpand').click(function () {
		$(this).toggleClass('open');
		$(this).parent().toggleClass('open'); // $('.members-scenelist div.mid-scene div.info')
	});
}



//-----------------------------------
// MAIN DOCUMENT.READY - on page load
//-----------------------------------

$(document).ready(function() {

	initWallpaper();
	
	if (plumperPassConfig.isTour) {
		showWarningPage();
	}
		
	initFavoritesButtons();
	initRateButtons();
	initSearch();

	if (plumperPass.activePage == 'home') {
		$("#rotator").jcarousel({
			scroll: 3,
			initCallback: rotator_initCallback,
			buttonNextHTML: null,
			buttonPrevHTML: null
		});
		initSitesButtons();
		initArrowExpand();
	}
	
	if (plumperPass.activePage == 'scenes' || plumperPass.activePage == 'models') {
		initGridButtons();	// Grid/List button events
		updateGridContent();	// ajax load first page of content
	}
	
	if (plumperPass.activePage == 'favorites') {
		initFavoritesModeButtons();	// Scenes/Models button events & ajax load first page of Favorites
	}

	if (plumperPass.activePage == 'scene') {
		initSceneButtons();
		// changeLinks('photosTab','^pictures');	// change pagenumber links in photos fragment to load pages using Ajax
		if (plumperPassConfig.isTour) setColorBox('photosTab', true, false);	// init colorbox for hires images
		$(".scroll-pane").jScrollPane();	// scroller for description
		rate_class.getCurrentRating();		// Ajax call to display the current scene rating
	}
	
	if (plumperPass.activePage == 'model') {
		$(".scroll-pane").jScrollPane();	// Scroll-pane in description
		initModelButtons();			// Scenes/Comments tabs
		rate_class.getCurrentRating();		// Ajax call to display the current scene rating
		initArrowExpand();
	}
	
	if (plumperPass.activePage == 'support') {
		if (window.location.search.indexOf('&status=1')!=-1) { 
			$("input.feedback_button.form_switch").hide(); 
		} else {
			$("input.feedback_button[type='reset']").hide();
			$("input.feedback_button.form_switch").click(function() {
				$("input.feedback_button.form_switch").addClass('notselected');
				$(this).removeClass('notselected');
				$(".feedback_form").hide();
				$('#'+$(this).attr('name')).show();
			});
		}
	}


	if (plumperPass.restoreState) restoreState();
	
	
	
	// IERadius fix - disabled
	/*---
	try {
		$('.ieradius').append('<div class="tl"></div><div class="tr"></div><div class="br"></div><div class="bl"></div>');
	} catch(e){};
	---*/
});



//--------------------------------------
// AJAX load & build request functions
//--------------------------------------

function updateFavoritesContent() {

	// Build AJAX request
	var request = 'favorites.php?go=show&sid=' + plumperPassConfig.searchRef
	var stateURL = '?favorites|' + plumperPass.favoritesMode;
	var tid=0, cats=0, v='';

	if (plumperPass.favoritesMode=='scenes') {
		cats = plumperPassConfig.scenesCategory;
		tid = plumperPassConfig.favoritesScenesSection; 
	} else if (plumperPass.favoritesMode=='models') {
		cats = plumperPassConfig.modelsCategory; 
		tid = plumperPassConfig.favoritesModelsSection;
	}
	request += '&tid='+tid;
	request += '&categories='+cats;
	
	// $('#gridContent').html(request);
	JLoadContent(
		request,	
		{ container: 'gridContent', 
		  pageTitle: ' Favorites > ' + plumperPass.favoritesMode
		}, 
		stateURL
	);
	
	plumperPass.restoreState = false; // We have already restored everything here, in a nested call within document.ready, no need to do it again at its end
}


function updateGridContent() {

	if (plumperPass.popState || plumperPass.restoreState) {
		// pre-set values of filter dropdowns and checkboxes upon state variables
		if (plumperPass.filterBySite) {
			$('#filterBySite a').removeClass('select').filter("[title='"+plumperPass.filterBySite+"']").addClass('select');
			$('#currentSite').html($('#filterBySite a.select').html());
		} else {
			$('#filterBySite a').removeClass('select').filter(':first').addClass('select');
			$('#currentSite').html('ALL');
		}
		if (plumperPass.sortBy) {
			$('#sortBy a').removeClass('select').filter('[rel='+plumperPass.sortBy+']').addClass('select');
		} else {
			$('#sortBy a').removeClass('select').filter(':first').addClass('select');
		}
		initCB('gridContent');
	} else {
		// update current state variables upon selected/checked values in filter dropdowns and checkboxes
		plumperPass.sortBy = $('#sortBy a.select').attr('rel');
		plumperPass.filterBySite = $('#filterBySite a.select').attr('title');
		plumperPass.avc = [];
		$('input[type="checkbox"][name="avc[]"]:checked').each(function(){
			v = $(this).val();
			plumperPass.avc.push(v);
		});
		insertMoreCB('gridContent');
	}
	

	// Build AJAX request
	var request = 'search.php?ref=' + plumperPassConfig.searchRef;
	var stateURL = '?' + plumperPass.activePage;
	var sid=0, cats=0, v='';

	if (plumperPass.activePage=='scenes') {
		cats = plumperPassConfig.scenesCategory;
		sid = plumperPassConfig.scenesGridSection; 
	} else if (plumperPass.activePage=='models') {
		cats = plumperPassConfig.modelsCategory; 
		sid = plumperPassConfig.modelsGridSection;
	}
	request += '&sid='+sid;
		
	if (cats) request += '&categories=' + cats;

	request += '&method=AND';

	if (plumperPass.sortBy) {
		request += '&so=' + plumperPass.sortBy;
	}

	request += '&q=';
	if (plumperPass.filterBySite) {
		request += '"' + plumperPass.filterBySite + '",';
		stateURL += '|' + plumperPass.filterBySite;
	}
	
	var searchTags = '';
	$.each(plumperPass.avc, function(i,v) {
		request += '"' + v + '",';
		searchTags += v + ',';
	});
	
	if (request) request = request.slice(0,-1);
	if (searchTags) {
		searchTags = searchTags.slice(0,-1);
		stateURL += '|' + searchTags;
	}
	
	/* this is not right... saving pageNr in state has to be reconsidered in full
	if (plumperPass.pageNr) {
		request += '&p=' + plumperPass.pageNr;
		stateURL += '|' + plumperPass.pageNr;
	}
	*/

	
	// $('#gridContent').html(request);
	JLoadContent(
		request,	
		{ container: 'gridContent', 
		  pageTitle: plumperPass.activePage + ' > ' + plumperPass.filterBySite + ' > ' + searchTags
		}, 
		stateURL
	);
	
	plumperPass.restoreState = false; // We have already restored everything here, in a nested call within document.ready, no need to do it again at its end
}


function insertMoreCB(C) {
	if (plumperPass.avMore && ($.inArray(plumperPass.avMore, plumperPass.avc)==-1)) {
		plumperPass.avc.push(plumperPass.avMore);
	}
	$.each(plumperPass.avc, function(i,v) {
		if ($('#'+C+' input[type="checkbox"][name="avc[]"][value="'+v+'"]').length < 1) {
			$('#last_label').before('<label><input type="checkbox" name="avc[]" class="avMore" checked value="'+v+'"> <u>'+v.replace('__',' ')+'</u> &nbsp;</label>');
		}
	});
}


function initCB(C) {
	insertMoreCB(C);
	if (plumperPass.popState || plumperPass.restoreState) {
		// uncheck all checkboxes first when restoring state, then check the needed ones
		$('#'+C+' input[type="checkbox"][name="avc[]"]').attr("checked", false);
	}
	$.each(plumperPass.avc, function(i,v) {
		$('#'+C+' input[type="checkbox"][name="avc[]"][value="'+v+'"]').attr("checked", true);
	});
}


function JLoadContent(lnk_load, O, stateURL) {
	var defaults = {
  		container	: 'gridContent',
  		colorBox	: function() { setColorBox(this.container, true, false); /* IERadiusInit(); */ },
  		linkReplacement	: function() { changeLinks(this.container); },
  		preloader	: 'over',
  		noCache		: true,
  		pageTitle	: '',
  		pageNr		: 1
  	}
  	
	if (O) $.extend(defaults,O);
	O = defaults;

  	if (O.preloader=='inline' || O.preloader==1) $('#'+O.container).html(getPreloader(1));
  	if (O.preloader=='over' || O.preloader==2) {
  		$('#'+O.container).prepend(getPreloader(2));
  		var w = $('#'+O.container).width();
  		if (w<200) w=1050;
  		if (plumperPass.activePage == 'home') {
  		   if (plumperPassConfig.isTour) {
  			$('#jload_preloader').css('left', 5).css('top', -14);
  		   } else {
  			$('#jload_preloader').css('left', w - $('#jload_preloader').width() - 65).css('top', 14);
  		   }
  		} else {
  			$('#jload_preloader').css('left', w - $('#jload_preloader').width() - 40).css('top', 46);
  		}
  	}
  	
  	if (O.noCache) {
  		var tm = new Date().getTime();
  		lnk_load = lnk_load+'&timecache='+tm;
  	}
  	
  	//console.log(lnk_load); 
  	// console.log(O.pageNr);
  	lnk_load = encodeURI(lnk_load);
	
	if (typeof(stateURL)=='undefined') {
		stateURL = '?' + History.getState().cleanUrl.split('?')[1];
	}
	
	if (lnk_load.indexOf('uvar=')==-1) {
		lnk_load += plumperPassConfig.uvarpass;
		stateURL += plumperPassConfig.uvarpass;
	}

  	var pageTitle = O.pageTitle?(plumperPassConfig.pageTitlePrefix + O.pageTitle):$(document).attr('title');
  	if (!plumperPass.popState && !plumperPass.restoreState) {
		plumperPass.pushState = true;
		History.pushState(plumperPass, pageTitle, stateURL);
	} else {
		plumperPass.pushState = false;
	}
	
  	$('#'+O.container).load(lnk_load, function(){ 
  		initPage(lnk_load, O.container); 
  		O.linkReplacement(); 
  		O.colorBox(); 
  		$(document).attr('title', pageTitle);
  	});
}


function changeLinks(C, fragment) {	
	$('#'+C+' a.pagenumbers.prevnext').remove();
	$('#'+C+' a.pagenumbers').each(function() {
		link = $(this).attr("href");
		if (link) {
			if ((plumperPass.activePage == 'scene') && typeof(fragment)!='undefined') {
				link = link.replace('&s=',fragment+'&s=');
			}
			$(this).attr("href", "javascript:;").attr("rel",link).click(function() {
				JLoadContent($(this).attr('rel'), {container: C, pageNr: $(this).html()}); 
				return false;
			});
		}
	});

	if (plumperPass.activePage == 'scenes' || plumperPass.activePage == 'models') {
		$('#'+C+' input[type="checkbox"][name="avc[]"]').click(updateGridContent);
		$('#'+C+' input[type="checkbox"][name="clear_avc"]').click(function(){
			$('input[type="checkbox"][name="avc[]"]:checked').attr("checked", false);
			plumperPass.avMore = '';
			updateGridContent();
		});
	} 

	if (plumperPass.activePage == 'scenes' || plumperPass.activePage == 'models' || plumperPass.activePage == 'home') {
		initArrowExpand();
	}
	
	initFavoritesButtons(C);
	initRateButtons(C);
}


function setColorBox(C, slideshowEnabled, slideshowAutostart ){
	// ColorBox for HiRes gallery
	// http://colorpowered.com/colorbox/
	
	if (plumperPass.activePage != 'scene') return;
	
	$("#"+C+" a[rel='gal']").colorbox({
		/* onClosed: function(){setColorBox(C, false, false)},  */
		transition: "fade", 
		slideshow: slideshowEnabled, 
		slideshowAuto: slideshowAutostart, 
		slideshowSpeed: 5000,
		loop: false,
		current: "image {current} of {total} on this page. [Esc] to close and go to next page.",
		scalePhotos: true,
		maxWidth: "100%",
		maxHeight: "100%",
		photo: true,
		title: "<a href='' target='_blank'>full image</a>",
		onComplete: function(){$('#cboxTitle a').attr('href',$.colorbox.element().attr('href'));}
	});
}


function initPage(L,C) {
	if (plumperPass.activePage == 'scenes' || plumperPass.activePage == 'models') {
		initGrids();		// apply vgrid plugin
		initCB(C);		// init avc checkboxes checked state
	} else if (plumperPass.activePage == 'favorites') {
		$('#favoritesMain').removeClass('members-scenelist').removeClass('members-modellist').addClass('members-'+plumperPass.favoritesMode.slice(0,-1)+'list');
	}
}


function getPreloader(t) {
	var preloaders = [
		'', 
		'Loading ...', 
		'<div id="jload_preloader" style="position: absolute; width: 130px; height: 26px; background-color: transparent; background-image: url(images/rgba/000000.1.png); Z-INDEX: 1000; padding: 10px 0 0 10px;"><img src="images/loader_progress.gif" title="Loading..." align="absmiddle" /></div>'
		];
	return preloaders[t];
}


//--------------------------------------
// MAS rating-related classes & functions
//--------------------------------------


var rate_class = {
	lid: 0,
	currentRating: 0,
	currentWidth: 0,
	nrVotes: 0,
	fullWidth: 150,
	ratingScale: plumperPassConfig.ratingScale,
	targetElement: '.currentRating',
	serverScript: plumperPassConfig.ajaxRateURL,
	f_text: 'Current rating ',

	getCurrentRating: function(lid, target) {
		thisClass = this;
		try {
			if (typeof(lid)=='undefined') lid = this.lid;
			if (typeof(target)=='undefined') target=this.targetElement;
			// lid = $(target).attr('id').slice(14);
			$.getJSON(this.serverScript+'?lid='+lid+'&mode=json&dtv=false&size='+this.fullWidth+'&callback=?', function(data) {
				// data = { rating: '0.00', nrVotes: '0', starWidth: '0', lid: '0' }
				thisClass.currentRating = data.rating * 2; // because ratingScale=5 in MAS and 10 in this site
				thisClass.currentWidth = data.starWidth;
				thisClass.nrVotes = data.nrVotes;
				thisClass.displayCurrentRating(target);
			});
		} catch(err) {}
	},

	displayCurrentRating: function(target, showNewRatingBox) {
		if (typeof(target)=='undefined') target=this.targetElement;
		$(target).html(this.currentRating);
		$('ul.star-rating li.current-rating').width(this.currentWidth);

		if (showNewRatingBox) {
			$('#rateBox div.your-rating strong').html(this.currentRating);
			$('#rateBox div.your-rating').show();
		}

		// var obj = document.getElementById('star_text_<?=$lid;?>');
		// if (obj) obj.innerHTML = this.f_text+rate;
	},

	rate: function(rate, lid, target) {
		thisClass = this;
		try {
			rate = rate/2; // because ratingScale=5 in MAS and 10 in this site
			if (typeof(lid)=='undefined') lid = this.lid;
			if (typeof(target)=='undefined') target=this.targetElement;
			$.getJSON(this.serverScript+'?go=save&r='+rate+'&lid='+lid+'&mode=json&dtv=false&size='+this.fullWidth+'&callback=?', function(data) {
				thisClass.currentRating = data.rating * 2;
				thisClass.currentWidth = data.starWidth;
				thisClass.nrVotes = data.nrVotes;
				thisClass.displayCurrentRating(target, true);
			});
		} catch(err) {}
		return false;
	},

	load_data: function(go, mode) {
		var e = document.createElement("script");
		url = this.serverScript;
		if (go != "") url = url+"?go="+go+"&lid="+lid;
		else url = url+"?go=get_rate&lid="+lid;
		if (mode != "") url = url+mode;
		url = url + '&size='+this.fullWidth;
		
		e.src = url;
		e.type="text/javascript";
		document.getElementsByTagName("body")[0].appendChild(e);
	}
}




//--------------------------------------
// Other MAS-related functions
//--------------------------------------

function jwplayerLoad(mediaFile, width, height, doPlay) {
	var jwp = jwplayer();

	// auto resize player to the dimensions of the loaded video
	width = parseInt(width); height = parseInt(height);
	if (width && height && (width!=jwp.getWidth() || height!=jwp.getHeight())) {
		setTimeout("jwplayerResize("+width+", "+height+")",100);
		$('.player').width(width).height(height);
		if (plumperPassConfig.isTour) {
			$('.videoplayerButton').css('top', height+130);
		} else {
			$('.videoplayerButton').css('top', height+170);
		}
	}
	// $('#descriptionOverlay').css('top', height+172-96).width(width-24).show();
	// $(".scroll-pane").jScrollPane();

	if (jwp.getState()=='PLAYING' || jwp.getState()=='BUFFERING') jwp.stop();
	var playListItem = { file: mediaFile, type: 'rtmp', streamer: plumperPassConfig.jwplayerStreamer };
	jwp.load(playListItem);
	if (typeof(doPlay)!='undefined' && doPlay) jwp.play(true);
}


function jwplayerResize(width, height) {
	var jwp = jwplayer();
	var jwpWidth = jwp.getWidth();
	if (typeof('jwpWidth')!='undefined') {
		jwp.resize(width, height); 
	} else {
		setTimeout("jwplayerResize("+width+", "+height+")",100);
	}
}


function jwplayerSeek(position) {
	var jwp = jwplayer();
	if (jwp.getState()=='IDLE') jwp.play(true);
	jwp.seek(position);
	// if (position < jwp.getDuration()) jwp.seek(position);
}


function search(what,where) {
	if (plumperPass.activePage == 'scenes' || plumperPass.activePage == 'models') {
		plumperPass.avMore = what;
		updateGridContent();
	} else {
		/*
		var SearchPageID = 333; // Replace this with the actual ID of the the search results template
		var HomePageID = plumperPassConfig.searchRef; // Replace this with the actual ID of this members area section
		var SearchAt = 0; // 0 - attribute values only; 1 - name/description only; 2 - both
		eval("self.location='search.php?q="+what+"&sid="+SearchPageID+"&ref="+HomePageID+"&at="+SearchAt+"'");
		*/
		
		var pathArray = window.location.pathname.split('/');
		if (pathArray[pathArray.length-1]!='') pathArray[pathArray.length-1]='';
		var sURL = pathArray.join('/') + '?';

		if (plumperPass.activePage == 'scene') {
			sURL += 'scenes|';
		} else if (plumperPass.activePage == 'model') {
			sURL += 'models|';
		} else if (plumperPass.activePage == 'home') {
			if (typeof('where')=='undefined' || (where!='scenes' & where!='models')) where='scenes';
			sURL += where + '|';
			if (plumperPass.homeSite!='' && plumperPass.homeSite!='ALL') {
				sURL += plumperPassConfig.fullSiteURL(plumperPass.homeSite) + '|';
			}
		} else if (plumperPass.activePage == 'favorites') {
			sURL += plumperPass.favoritesMode + '|'
		}
		sURL += what;
		sURL += plumperPassConfig.uvarpass;
		eval("self.location='"+sURL+"'");
	}
}




///////////////////////////////////////////////////////////////////////////////
//--------------------------------------
// jQuery Extensions
//--------------------------------------
///////////////////////////////////////////////////////////////////////////////

/**
 * jQuery.support.cssProperty
 * To verify that a CSS property is supported (or any of its browser-specific implementations)
 *
 * @param string p - css property name
 * [@param] bool rp - optional, if set to true, the css property name will be returned, instead of a boolean support indicator
 *
 * @Author: Axel Jack Fuchs (Cologne, Germany)
 * @Date: 08-29-2010 18:43
 *
 * Example: $.support.cssProperty('boxShadow');
 * Returns: true
 *
 * Example: $.support.cssProperty('boxShadow', true);
 * Returns: 'MozBoxShadow' (On Firefox4 beta4)
 * Returns: 'WebkitBoxShadow' (On Safari 5)
 */
$.support.cssProperty = (function() {
  function cssProperty(p, rp) {
    var b = document.body || document.documentElement,
    s = b.style;

    // No css support detected
    if(typeof s == 'undefined') { return false; }

    // Tests for standard prop
    if(typeof s[p] == 'string') { return rp ? p : true; }

    // Tests for vendor specific prop
    v = ['Moz', 'Webkit', 'Khtml', 'O', 'ms', 'Icab'],
    p = p.charAt(0).toUpperCase() + p.substr(1);
    for(var i=0; i<v.length; i++) {
      if(typeof s[v[i] + p] == 'string') { return rp ? (v[i] + p) : true; }
    }
  }

  return cssProperty;
})();



