(function($){

	$.extend({

		tlavideo: {

			/* Content ends here */

			// user reviews functionality
			// added 11.12.07
			// msb

			userReviews: function() {
				$(".userReview").click( function() {
					$(this.parentNode).hide();
				});

				var $theSubmit = $("#reviewForm input[@type = 'submit']");
				var $theAlias = $("#reviewForm input[@name = 'alias']");
				var $theReviewTitle = $("#reviewForm input[@name = 'title']");
				var $theReview = $("#reviewForm textarea[@name = 'review']");
				var $theFormView = $("#reviewForm input[@name = 'view']");
				var $theEmail = $("#reviewForm input[@name = 'email']");
				
				$theSubmit.click( function() {
					try{
					if ($theReviewTitle.val().length <= 0) {
						$theReviewTitle.prev().html("<strong>Title of Your Review:</strong> <span class='ajaxFormRequired'>(required)</span>"); }
					else if ($theReview.val().length <= 0) {
						$theReview.prev().html("<strong>Your Review:</strong> <span class='ajaxFormRequired'>(required)</span>"); }
					else if ($theEmail.length && ($theEmail.val().length<=0 || !isEmail($theEmail.val()))){
						$theEmail.prev().html("<strong>Your Email:</strong> <span class='ajaxFormRequired'>(" + 
												($theEmail.val().length<=0?"required":"invalid") 
												+")</span>"); }
					else {
						$theSubmit.val("Saving...").attr("disabled","disabled");
						var $vars = $("#userReviewForm").attr("action");
						$vars = $vars.split("?");
						$vars = $vars[1];

						var thisData = {
							title: $theReviewTitle.val(),
							review: $theReview.val(),
							view: $theFormView.val(),
							alias: $theAlias.val()
						};
						if($theEmail.length){
							thisData.email=$theEmail.val();
						}
						$.ajax({
							type: "POST",
							url: "/ajax/ajax_userReviews.cfm?" + $vars,
							data: thisData,
							error: function(msg) {
								alert("Error: " + msg.responseText);
							},
							success: function(msg) {
								$(".userReviewTitle").html("Thank you for your submission!").css("text-transform", "uppercase");
								$("#reviewForm")
									.before("<p>Your submission will be reviewed by our editors and, if accepted, will be posted on our web site shortly. We reserve the right to reject submissions that we deem offensive or obscene. Once posted, we are unable to remove or edit submissions, under any circumstances.</p>");
								showReviewForm(false);
							}
						});
					}

					$(".ajaxFormRequired").css({ color: "red", "font-weight": "bold" });
					} catch(err) {
						alert("Sorry, there was an error. Try again.");
					}
					return false;
				});

			}, /* end user reviews */
			
			trackFederatedLinks: function(linkContainerSelector) {
				/*
				 * pass google analytics session information in links to other domains within our
				 * federation.
				 */
				 if($.tlavideo.pageTrackerDomains && $.tlavideo.pageTrackerDomains.length)
				{
					for (var i=0; i<$.tlavideo.pageTrackerDomains.length; i++)
					{
						$(linkContainerSelector + ' a.federated')
							.click(function() {
								pageTracker._link(this.href);
								return false;
							});
					}
				}
			}, /* end track federated links */
			
			rawBottom: function() {
				var bodyHeight = $('body').height();
				var windowWidth = $(window).width();
				var bodyWidth = $('body').width();
				var left = '-' + (windowWidth - bodyWidth)/2 + 'px';
				if (bodyHeight > 1384) {
					$('body.skinema span.bkg-btm, body.cult span.bkg-btm').show();
					$('body.skinema span.bkg-btm, body.cult span.bkg-btm').css({
						'width': windowWidth + 'px',
						'position': 'absolute',
						'left': left,
						'bottom': '0px',
						'display': 'block'
					});
				}
				$(window).resize(function(){
					var newWindowWidth = $(window).width();
	  				$('body.skinema span.bkg-btm, body.cult span.bkg-btm').css({
						'width':newWindowWidth + 'px'
					});
				});
				
				//allow chaining
				return this;
			},
			
			polls: function() {
				$(".polling-question").each(function(){
					var $poll=$(this)
					var pollId=$poll.attr("id");
					if(document.cookie.indexOf(pollId+"=")>=0)
					{
						$.get("/survey/pollModuleResults.cfc",
							{method : "display", query_id : pollId.match(/\d+/)},
							function(data){$poll.html(data);})
					} 
				})
				.find("a.polling-results").click(function(){
					window.open($(this).attr('href'),'',
					'status=no,menubar=no,width=200,height=500,scrollbars=yes');
					return false;
				});
				//allow chaining
				return this;
			},
			
			windowTabs: function() {
				$('ul.window-tabs').each(function() { //check every set of window tabs on the site
			
					//if the anchor tag has a class we're working in the right set of window tabs
					if ($(this).next().hasClass('hidden-content')) {
						
						//if we're in the VOD Purchases tab we load the download history into the ajax container
						if ($(this).children('#VODDownloadHistory').hasClass('current')) {
							var loadingHTML = "<img src='/Skins/graphics/70/elements/loader.gif' style='margin: 0 400px;'/>";
							loadingHTML += "<p style='margin: 0px 403px; color: #CCCCCC;'>Loading</p>";
							$('#vodAjaxContainer').append(loadingHTML);
							
							$.ajax({
								url: '/customer/VODDownloadHistory.cfm',
								data: {
									dm: isTLADMInstalled()
								},
								success: function(data){
									if ($('#VODDownloadHistory').hasClass('current')) {
										$('#vodAjaxContainer').html(data);
									}
								},
								timeout: 20000,
								cache: false
							});
						} else if ($(this).children('#VODFavorites').hasClass('current')) {
							var loadingHTML = "<img src='/Skins/graphics/70/elements/loader.gif' style='margin: 0 400px;'/>";
							loadingHTML += "<p style='margin: 0px 403px; color: #CCCCCC;'>Loading</p>";
							$('#vodAjaxContainer').append(loadingHTML);
							
							$.ajax({
								url: '/customer/VODFavorites.cfm',
								data: {
								},
								success: function(data){
									$('.window-tabs .current').removeClass('current');
									$('#VODFavorites').addClass('current');
									$('#vodAjaxContainer').html(data);
									
								},
								timeout: 20000,
								cache: false
							});
						}
						
							//add a listener to the tabs and load data via ajax on click
							$('li a.download-history, li a.rental-history, li a.ppm-history, li a.vod-favorites ').click(function (event) {
									event.preventDefault();
									var parentTab = $(this).parent();
									var parentTabID = $(parentTab).attr('id');
									var tabToLoad = '/customer/' + parentTabID + '.cfm?';
									$('#vodAjaxContainer').empty();
									$('#vodAjaxContainer').append(loadingHTML);
									$.ajax({
										cache: false,
										url: tabToLoad,
										success: function(data){
											if ($(parentTab).hasClass('current')) {
												$('#vodAjaxContainer').html(data);
											}
										},
										cache: false,
										timeout: 20000,
										error: function(XMLHttpRequest, textStatus, errorThrown){
											if (textStatus) {
												var errorText = 'We have encountered a/n ' + textStatus + ' with your request.'
												if (errorThrown) {
													var thrownText = 'An error was thrown.  It looks like this:' + errorThrown;
													errorText += thrownText;
												}
												$('#vodAjaxContainer').html(errorText);
											}
										}
									});
							});
						
						
						//shows all tabs, non javascript users will just see the tab marked current with all the tabbed info shown
						$(this).children('li').show();
						if (! $(this).children('li:only-child').length) {
							$('li.current').children('span.arrow').show(); //show the hidden arrows on the page
						}
						
						// create a variable based off every anchor tag's class and hide all associated divs
						$(this).children('li').children('a').each(function() {
							var anchorClass = $(this).attr('class');
							$('div#' + anchorClass).addClass('toggled-info').hide();
						});
						
						// show the first div that cooresponds to the first li or li.current class (they're the same)
						var firstTab = $(this).children('li.current').children('a').attr('class');
						$('div#' + firstTab).show();
						
						// click function to toggle tabbed info
						$(this).children('li').children('a').click(function() {
							return $.tlavideo.selectWindowTab($(this));
						}); 
						
						// if it's no the only tab, remove full tab class
						if (! $(this).children('li:only-child').length) {
							$(this).removeClass('full-tab');
							$(this).next('div').addClass('tabbed');
						}
						
						// show the fisrt tab as current
						$(this).children('li').removeClass().show();
						$(this).children('li:first').addClass('current');
					}
					
				});
				
				//allow chaining
				return this;
			},
			
			selectWindowTab: function($tab){
				var anchorClass = $tab.attr('class');
				$tab.parent('li').siblings('.current').children('span.arrow').hide();
				$tab.parent('li').siblings('.current').removeClass('current').show();
				$tab.parent('li').addClass('current');
				$tab.siblings('span').show();
				$('.toggled-info').hide();
				$('div#' + anchorClass).show();
				return false;
			},
			
			bigForm: function(){
				$("div.bigform").each(function(){
					$("div#shipping.empty").each(function(){
						$('input#shipsame').attr('checked', 'true');
						$('div#shipping').hide();
						$('div#shipping input, div#shipping select').attr('disabled', 'disabled');
					});
					$('input#shipsame').click(function(){
						if ($(this).is(':checked')) {
							$('div#shipping input, div#shipping select').attr('disabled', true);
							$('div#shipping').hide();
						} else {
							$('div#shipping input, div#shipping select').removeAttr('disabled');
							$('div#shipping').show();
						}   
					});

				});
				
				//allow chaining
				return this;
			},
			marquee: function() {
				
			if (($('div#marquee').length)) {
		
			/*********
			 * setup *
			 *********/
				
				/** show all articles, overrides js free one article functionality **/
				$('div#marquee div.marquee-group div.article-sequence-group').show();
				
				/** add initial active class for the slideshow - pertains to banners & banner number **/
				$('div#marquee div.marquee-group div.article-sequence-group:first-child').addClass('active');
				
				/** if there's more than one group **/
				if (! $('div#marquee ul#marquee-group-name').children('li:only-child').length) {
				
					/** show the article group list, set the first child to active & make room for the info area **/
					$('div#marquee ul#marquee-group-name').show();
					$('div#marquee ul#marquee-group-name').children('li:first').addClass('active');
					$('div#marquee span.ul-corner').show();
				} else {
					$('div#marquee span.ul-corner').show().addClass('banner-mask-right');
				}
				
				/** show the first article group **/
				var firstArticle = $('div#marquee ul#marquee-group-name').children('li:first)').children('a').attr('class');
				var $firstArticleGroup = $('div#marquee div.' + firstArticle);
				$firstArticleGroup.addClass('current').show();
				
				/** check to see if the first gallery matches the first approved gallery **/
				if (!$firstArticleGroup.hasClass('first')) {
					$('div.marquee-group').removeClass('first');
					$firstArticleGroup.addClass('first');
				}
				
				/** create lpage article swap **/
				$('div#marquee-groups div.marquee-group').each(function(){
					$(this).append("<div class='lpage-article-swap'></div>");
					$(this).children('div.article-sequence-group').each(function(i){
						var articleID = $(this).children('div').attr('id');
						$(this).parent().children('div.lpage-article-swap').append("<span class='" + articleID + "'>" + (i + 1) + "</span>");
						$(this).parent().children('div.lpage-article-swap').children('span:eq(0)').addClass('active');
						$('div#marquee div.lpage-article-swap span:eq(0)').addClass('active');
					});
				});
				
			/************************
			 * start the slideshow  *
			 ************************/
				
				playSlideShow = setInterval('marqueeSlideShow();', 5000);
				
			/*******************
			 * hover functions *
			 *******************/
			
				$('div#marquee div.lpage-article-swap span').hover(function(){
					if (typeof(playSlideShow) != 'undefined') {
						clearInterval(playSlideShow);
					}
					
					/** remove any slideshow classes and make the hovered number active **/
					$('div#marquee div.current div.lpage-article-swap span').removeClass('active').removeClass('last-active').removeClass('second');
					$(this).addClass('active').css('cursor', 'pointer');
					
					/** figure out the selected banner  **/
					var articleNumber = $(this).attr('class');
					var articleNumberNew = articleNumber.replace(' active', '');
					var selectedArticle = 'div#marquee div.current div.article-sequence-group div#' + articleNumberNew + ', div#marquee div.current div.article-sequence-group div#' + articleNumberNew + '_2';
					
					/** hide all articles **/
					$('div#marquee div.current div.article-sequence-group div.lpage-article').css({
						opacity: 0.0
					}); 
					
					/**hide all articles parents get a reset z-index (for ie) & remove active class **/
					$('div#marquee div.current div.article-sequence-group').css({
						"z-index": 0
					}).removeClass('active'); 
					
					/** show the selected  banner **/
					$(selectedArticle).css({
						opacity: 1.0,
						"z-index": 10
					});
					
					/** give it's parent a higher z-index (for ie) **/
					$(selectedArticle).parent('div.article-sequence-group').css({
						"z-index": 10
					}); 
				
				}, function(){});
			
				$('div#marquee ul#marquee-group-name li a').hover(function(){
					
					/** remove any slideshow classes on the articles **/
					$('div#marquee div.article-sequence-group, div#marquee div.lpage-article-swap span').removeClass('active').removeClass('last-active').removeAttr('style').show();
					
					/** add the active class to each group **/
					$('div#marquee div.marquee-group div.article-sequence-group:first-child, div#marquee div.lpage-article-swap span:first-child').addClass('active');
					
					/** make sure the articles are visible **/
					$('div#marquee div.article-sequence-group div.lpage-article').removeAttr('style');
					
					/** if the slideshow is playing stop it **/
					if (typeof(playSlideShow) != 'undefined') {
						clearInterval(playSlideShow);
					}
					
					/** hide all groups and remove current class **/
					$('div#marquee div.marquee-group').hide().removeClass('current');
					
					/** figure out the new selected gallery **/
					var articleGroupId = $(this).attr('class');
					var selectedArticleGroup = 'div#marquee div.' + articleGroupId;
					
					/** show the selected gallery, add class current and highlight the new arrow */
					$(selectedArticleGroup).show().addClass('current');
					$('div#marquee ul#marquee-group-name li').removeClass('active');
					$(this).parent().addClass('active');
					
					playSlideShow = setInterval('marqueeSlideShow();', 5000);
					
					/** make sure the right corner is showing **/
					
					if (!$('div#marquee ul#marquee-group-name').children('li:only-child').length) {
						if ($('ul#marquee-group-name li:first').hasClass('active')) {
							$('div#marquee span.ul-corner').css('background', 'url(/skins/graphics/70/tlaraw-new/marquee/ul-corner-first.gif) 0 0 no-repeat');
						} else {
							$('div#marquee span.ul-corner').css('background', 'url(/skins/graphics/70/tlaraw-new/marquee/ul-corner.gif) 0 0 no-repeat');
						}
					}
					
				}, function(){});
				
				$('div#marquee ul#marquee-group-name li a').click(function(){return false;});
				
				
			}
				
			//allow jQuery chaining
			return this;
				
			}, //end marquee
			
			vodScenes: function(){
				
				var msie6 = $.browser.msie && /MSIE 6\.0/i.test(window.navigator.userAgent) && !/MSIE 7\.0/i.test(window.navigator.userAgent);

				if($('div#scenes').length) {
					var sceneWidth = $('div.vod-thumb img').width();
					var $scene = $('div.vod-thumb');
					if (sceneWidth < 130) {
						if (msie6) {
							$scene.css('margin', '8px 1px');
						} else {
							$scene.css('margin', '8px 2px 8px 1px');
						}
						
					} else if (sceneWidth > 130 && sceneWidth < 200) {
						if (msie6) {
							$scene.css('margin', '8px 1px');
						} else {
							$scene.css('margin', '8px 2px');
						}
					}
				}
				
				//allow jQuery chaining
				return this;
			
			}, //end vodScenes
			
			siteTabs: function(){
				$('ul#main-nav a, ul#main-nav li.beta-flag, #navigation ul a').hover(function(){
					$(this).oneTime(700, "hoverSiteTabs", function(){
						if ($(this).hasClass('beta-flag')) {
							$(this).children('span.tooltip').show();
							var tooltipWidth = $(this).children('span.tooltip').width();
							var tooltipHeight = $(this).children('span.tooltip').height();
							var newCSS = {height:tooltipHeight, width:tooltipWidth};
							$(this).css(newCSS);
							$(this).siblings().css('left', tooltipWidth - 51);
						} else {
							$(this).siblings('span.tooltip').show();
						}
					});
				}, function(){
					if ($(this).hasClass('beta-flag')) {
						$(this).children('span.tooltip').hide();
						$(this).removeAttr('style');
						$(this).siblings().removeAttr('style');
					} else {
						$(this).siblings('span.tooltip').hide();
					}
					$(this).stopTime("hoverSiteTabs");
				});
	
				$('a#affiliateLinkBack').click(function(){
					tipToggle($(this));
					return false;
				});
				
				function showToolTip($this) {
					var linkHref = $('a#affiliateLinkBack')
						.attr('href')
						.replace(/\&/g,"&amp;amp;");
					var tooltipMarkup = '<span class="tooltip"><span class="arrow"></span><span class="close"></span>'+linkHref+'</span>';
					$this.parent('li').append(tooltipMarkup).css('position', 'relative');
					var tooltipWidth = $this.siblings('.tooltip').width();
					var halfWidth = -((tooltipWidth/2)+20);
					$this.siblings('.tooltip').css('margin-left', halfWidth);
					$this.siblings('.tooltip').children('.close').click(function(){
						$(this).parent('.tooltip').remove();
					});
				}
				
				function tipToggle($this) {
					var $tooltip = $this.siblings('.tooltip');
					if ($tooltip.length) {
						$this.siblings('.tooltip').remove();
					} else {
						showToolTip($this);
					}
				}
				
				//allow jQuery chaining
				return this;
				
			}, //end siteTabs
			
			suckerFish: function() {

				var $sfLi = $('ul.suckerfish li');
	
				$sfLi.hover(function(){
					$(this).addClass('sfhover');
				}, function() {
					$(this).removeClass('sfhover');
				});
				
				$sfLi.each(function(){
					if ($(this).children('ul').length) {
						$(this).addClass('sf-arrow');
					} else {
						$(this).addClass('no-sub-ul');
					}
				});
				
				// fix for ie6
				var $midUl = $('ul.suckerfish ul');
				$midUl.each(function(){
					var ulWidth = $(this).width();
					$(this).children('li').css({width: ulWidth});
				});
				
				//allow jQuery chaining
				return this;
			
			}, //end suckerFish
			
			hideRefineSearch: function(){
				
				var $refineHeading = $('div#left-sidebar form#advancedSearch h3');
				var $midSearchHook = $('div#left-sidebar #adv-search-submitted');
				
				if ($midSearchHook.length) {
					var refineLink = '<a href="#" class="highlight">Refine Your Search -</a>';
					$refineHeading.html(refineLink);
					$refineHeading.children('a').toggle(function(){
						$(this).parents('h3').siblings().hide();
						$(this).html('Refine Your Search +');
					}, function(){
						$(this).parents('h3').siblings().show();
						$(this).parents('h3').siblings('.summary').hide();
						$(this).html('Refine Your Search -');
					});
				} else {
					var refineLink = '<a href="#" class="highlight">Refine Your Search +</a>';
					$refineHeading.html(refineLink);
					$refineHeading.siblings().hide();
					$refineHeading.children('a').toggle(function(){
						$(this).parents('h3').siblings().show();
						$(this).parents('h3').siblings('.summary').hide();
						$(this).html('Refine Your Search -');
					}, function(){
						$(this).parents('h3').siblings().hide();
						$(this).html('Refine Your Search +');
					});
				}
				
				//allow jQuery chaining
				return this;
			
			},
			
			formAutoFocus: function() {
				
				$('input#searchtext').focus();
				$('div#login input[name=email]').focus();
				
				//allow jQuery chaining
				return this;
			}
			
		}, /* end tlavideo */


		/* Copyright (c) 2006 Mathias Bank (http://www.mathias-bank.de)
		 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
		 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
		 *
		 * Thanks to Hinnerk Ruemenapf - http://hinnerk.ruemenapf.de/ for bug reporting and fixing.
		 */

		getURLParam: function(strParamName){
			var strReturn = "";
			var strHref = window.location.href;
			var bFound=false;

			var cmpstring = strParamName + "=";
			var cmplen = cmpstring.length;

			if ( strHref.indexOf("?") > -1 ) {
				var strQueryString = strHref.substr(strHref.indexOf("?")+1);
				var aQueryString = strQueryString.split("&");
				for ( var iParam = 0; iParam < aQueryString.length; iParam++ ){
					if (aQueryString[iParam].substr(0,cmplen)==cmpstring){
						var aParam = aQueryString[iParam].split("=");
						strReturn = aParam[1];
						bFound=true;
						break;
					}

				}
			}
			if (bFound==false) return null;
			return strReturn;
		}

	});

	$.fn.extend({

		center: function() {
			return this.each(function() {

				var myWidth		= $(this).outerWidth(),
					myHeight	= $(this).outerHeight(),
					winWidth	= $(window).width(),
					winHeight	= $(window).height(),
					leftScroll	= $(window).scrollLeft(),
					topScroll	= $(window).scrollTop();

				var newTop = ((winHeight/2)-(myHeight/2))+topScroll,
					newLeft = ((winWidth/2)-(myWidth/2))+leftScroll;

				if (newTop < 0) {
					newTop = 0;
				} else if (newTop < topScroll) {
					newTop = topScroll;
				}

				if (newLeft < 0) {
					newLeft = 0;
				} else if (newLeft < leftScroll) {
					newLeft = leftScroll;
				}

				$(this).css('position','absolute').css('top',newTop).css('left',newLeft);

			});
		}

	});

	$(function(){ /* onload begins here */

	//wishlist module
	var wishlists = $('div.wishlist-module');
	$(wishlists).each(function(){
		var count = $(this).html();
		count = $.trim(count);
		$(this).addClass(count);
		$('.wishlist-module.'+count).empty();
		$.ajax({
			type : 'GET',
			url : '/wishlist/landingModule.cfc',
			data : 'method=products&count='+count,
			dataType: 'json',
			success : function(data) {
				if (!data[0]) {
					return false;
				}
				$('.wishlist-module').addClass('clearfix');
				if (count % 4 == 0) {
					$('.wishlist-module').addClass('product-row');
					$('.wishlist-module').addClass('col4');	
				}
				for (i in data) {
					var title = data[i]['TITLE'];
					var link = data[i]['LINK'];
					var image = data[i]['IMAGE'];
					var price = data[i]['PRICE'];
					var id = data[i]['ID'];
					var view = data[i]['VIEW'];
					var sku = escape(data[i]['SKU']);
					var addToCart = "<a href='../cart/viewcart.cfm?v="+view.toString()+"&task=add&sku="+sku+"'>";
					addToCart += "<img src='/skins/graphics/70/buttons/cart-add.png' /></a>";
					var currProduct = "<div class='product'><div class='thumb'><a href='"+link+"'><img src='"+image;
					currProduct += "'tooltip='"+id+"'/></a></div>";
					currProduct += "<div class='product-info'><div class='title'><a href='"+link+"'>"+title+"</a></div>";
					currProduct +="<div class='price'>"+addToCart+"</div><div class='price'>"+price+"</div></div>";
					currProduct +="<div class='clear-fix'></div></div>"
					$('.wishlist-module.'+count).append(currProduct);
				}
				$('.wishlist-module.'+count).parents('.wishlist').show();
			}
		});
	});
	
	//coverflow module
	(function(){
		$('.coverFlow').each(function(){
			var moreText = $(this).parents('.article-sequence-group').children('.section-heading').children('a:first').html();
			var moreLink = $(this).parents('.article-sequence-group').children('.section-heading').children('a.more-link').attr('href');
			var moreLinkText = "<div class='coverFlowItem'><a class='see-all-products' href='" + moreLink + "'><span>See All</span>";
			moreLinkText += moreText +"</a></div>";
			$('.mover',this).append(moreLinkText);
			numProducts = $('.coverFlowItem',this).length;
			var slides = Math.floor(numProducts / 4);
			var moverWidth = slides * 660;
			if (numProducts % 4 != 0) {
				moverWidth += 660;
				slides++;
			}
			$(this).addClass(slides.toString());

			$('.mover',this).css({width : moverWidth.toString() + 'px'});
		});
		$('.mover').addClass("1");
		var moveLeft = function(event){
			$('.right',$(event).parent()).fadeTo(10, 1.0);
			var mover = $('.mover',$(event).parent());
			var counter = parseInt($(mover).attr('class').split(' ')[1]);
			var slides = parseInt($(event).parent().attr('class').split(' ')[1]);
			if (counter > 1) {
				$(mover).animate({left: '+=616'}, 600, 'swing', function(){
					if (counter === 2) {
						$('.left',$(event).parent()).fadeTo('fast',0.3);
				}
				});
				$(mover).removeClass(counter);
				$(mover).addClass((counter - 1).toString());
			} else {
				$('.left',$(event).parent()).fadeTo(10, 0.3);
			}
		}
		var moveRight = function(event){
			$('.left',$(event).parent()).fadeTo(10, 1.0);
			var mover = $('.mover',$(event).parent());
			var counter = parseInt($(mover).attr('class').split(' ')[1]);
			var slides = parseInt($(event).parent().attr('class').split(' ')[1]);
			if (counter <= slides - 1) {
				$(mover).animate({left: '-=616'}, 600, 'swing', function() {
					if (slides - counter === 1) {
					$('.right',$(event).parent()).fadeTo('fast', 0.3);
				}
				});
				$(mover).removeClass(counter);
				$(mover).addClass((counter + 1).toString());
			} else {
				$('.right',$(event).parent()).fadeTo(10, 0.3);
			}
		}
		$('.coverFlow .left').fadeTo(10, 0.3);
		$('.coverFlow .left').click(function(event){
			moveLeft(event.target);
		});
		$('.coverFlow .right').click(function(event){
			moveRight(event.target);
		});
	})();
		//if we're not using ie6 use tooltips
		if (typeof document.body.style.maxHeight !== "undefined") {
		
			//tool tips for top navigation
			var gayTipText = 'TLAGay.com is your online destination for the best in gay cinema, adult entertainment, VOD, books, toys & much more.';
			var rawTipText = 'Looking for the best in Adult DVDs, VOD and Sex Toys for men, women and couples? TLAraw.com is your destination.';
			var cultTipText = 'TLACult.com is your online destination for horror movies, cult classics, exploitation cinema and much more on DVD.';
			var moviesTipText = 'Your DVD and VOD destination for the latest Hollywood hits, offbeat Independent films, International Cinema and documentaries.';
			var toolTip = '<div id="navToolTip"></div>';
			
			//add listeners to nav tabs
			$('#tla-gay-nav a, #tla-raw-nav a, #tla-cult-nav a, #tla-movies-nav a').hover(function(event){
				$('div#navToolTip').fadeOut();
				
				//get the id of the hovered tab to choose correct text
				var hoveredTab = $(this).parent().attr('id');
				hoveredTab = hoveredTab.split('-');
				hoveredTab = hoveredTab[1];
				var chooseTab = '';
				switch (hoveredTab) {
					case 'gay':
						chooseTab = gayTipText;
						break;
					case 'raw':
						chooseTab = rawTipText;
						break;
					case 'cult':
						chooseTab = cultTipText;
						break;
					case 'movies':
						chooseTab = moviesTipText;
						break;
				}
				
				//get dimensions of tab to place tooltip accordingly
				var tabLocation = $(this).offset();
				$(toolTip)
					.appendTo('body')
					.html(chooseTab)
					.addClass('active')
					.css({
						top: tabLocation.top + 30,
						left: tabLocation.left - 60
					})
					.fadeIn();
			}, function(){
				$('div#navToolTip').fadeOut();
				$('div#navToolTip').remove();
			});
		}
		
		//test to see if window is big enough for link to this
		if ($(window).width() > 1000) {
		
		var linkCount = 0;
		
		//link to this pop-up
			$('#link-to-this').click(function(event){
				
				event.preventDefault();
				if (linkCount === 0) {
					$('#link-to-this-slider').animate({top: '+=30'}, 200);
					linkCount = 1;
				} else {
					$('#link-to-this-slider').animate({top: '-=30'}, 200);
					linkCount = 0;
				}
			});
		} else {
			$('#link-to-this, #link-to-this-slider').remove();
		}
		//test to see if there is a trailer playing and then overwrite external interface callback to fix IE error
		var setRemoveCallback = function() {
			__flash__removeCallback = function(instance, name) {
	    		if(instance) {
				instance[name] = null;
	    	}
	    	}
	    	window.setTimeout(setRemoveCallback, 1000);
		} 
		$('#trailer').each(setRemoveCallback);
		
		var legacyPlayer = function(start,movieID){
			window.open("/vod/player/player.cfm?id="+ movieID +"&start="+start+"&res=1",
						'vodplayer',
						'toolbar=0,location=0,directories=0,status=0,menubar=0,top=0,left=0,scrollbars=1,resizable=1,width=800,height=500');
		}
		var popupPlayer = function (start,movieID) {
			var windowOpts = ['height=530', 'width=750', 'scrollbars=yes', 'toolbar=no', 'location=no', 'menubar=no'];
    		var popup = window.open('/VOD/popupSilverlight.cfm?start=' + start + '&movie=' + movieID,'',windowOpts.join());
		}
		var standardPlayer = function(start,movieID){

					if($('div#silverlightControlHost').length) {
						var movie = $('div#silverlightControlHost');
						$(movie).remove();

					} else {
						$('h2.title').after('<div id="movieWrapper" style="height: 205px; background: white; margin-bottom: 10px; "></div>');
						$('#movieWrapper').animate({ 'height' : '405px'}, 1000);
					}
					$.ajax({
					  url: '/sitelib/vod/stream.cfc?id=' + movieID + '&method=asx',
					  success: function(data) {
						var player = '';
						if (!Silverlight.isInstalled('3.0')) {
							player += '<div style="margin: 100px auto; width: 400px; padding: 20px; background: white;text-align: center;"><p>';
							player += 'We have detected that you are using an older version of Silverlight.  Please upgrade by clicking here to ';
							player += '<a href="http://www.microsoft.com/getsilverlight/">update Silverlight</a></p></div>';
							$('#movieWrapper').css('padding-top','100px').html(player);
							return false;
						} else {
							$('#movieWrapper').append('<div id="silverlightControlHost"></div>');
					    	var movie = $('div#silverlightControlHost');
					    	$(movie).css({ 'height' : '405px', 'margin' : '0px 0px 15px'});
					    	player += '<object id="playerObj" data="data:application/x-silverlight," type="application/x-silverlight-2" height="402" width="715">';
					    	player += '<param name="source" value="/resources/VideoPlayerM1_1.xap"/>';
					    	player += '<param name="minRuntimeVersion" value="4.0.50917"/>';
					    	player += '<param name="onerror" value="onSilverlightError" />';
					    	player += '<param name="background" value="white" />';
					    	var movieLink = data.replace(/&/gi,'&amp;');
					    	player += '<param name="initParams" value="start=' + start + ',auto=true,m=' + movieLink + '" />';
					    	player += '</a></object>';
						}
					    $(movie).html(player);
					    	if ($('h2 a').length < 1) {
					    		var loc = window.location.href;
					    		loc = loc.split('#');
					    		loc = loc[0];
					    		$('h2').append('<a href="' + loc + '" style="font-size: 14px; color: #c00;" id="close">close player</a>');
					    		$('#player-speed').css({'float':'left','display':'inline-block'})
					    		.width('400px')
					    		.after('<a href="" class="popup-video" style="float: right; display: block; text-decoration:none;">View in Popup Player</a><div style="clear: both;"><a href="/support/supportOption.cfm?v=1&sn=1&supID=43" style="display: inline; float: right; text-decoration:none;">Need Help? Read our FAQ.</a></div>');
					    		$('a.popup-video').click(function(event){
					    			var playerObj = document.getElementById('playerObj');
					    			if (playerObj.Content.Page.State === 'Playing') {
					    				playerObj.Content.Page.TogglePlay();
					    			}
					    			event.preventDefault();
					    			var position = Math.floor(playerObj.Content.Page.Position).toString();
					    			var height = $('div#silverlightControlHost').css('height');
						    		var movie = $('#playerObj param[name="initParams"]').attr('value');
						    		movie = movie.split('m=');
						    		movie = movie[1];
						    		var movieParams = [position,height,movie];
						    		for (i in movieParams) { 
						    			$('#silverlightControlHost').addClass(movieParams[i]);
						    		}
					    			var numScenes = $('div.vod-thumb a').length;
					    			var windowHeight = parseInt(height) + (240 + ((Math.ceil(numScenes / 7) - 1) * 100));
					    			if (windowHeight > 840 ) { windowHeight = 840; }
					    			var windowOpts = ['height=' + windowHeight.toString(), 'width=770', 'scrollbars=yes', 'toolbar=no', 'location=no', 'menubar=no'];
					    			var popup = window.open('/VOD/popupSilverlight.cfm','',windowOpts.join());
					    		});
					    		
					    }
					    
					    	$('a.favorites').remove();
							var videoPlayerLoaded=function(sender) {
							    if (sender.hasOpenMedia) {
							        onMediaInfoAvailable(sender)
							    } else {
							        sender.addEventListener("MediaOpened",onMediaInfoAvailable);
							    }
							}
							var onMediaInfoAvailable=function(sender) {
								var objHeight = parseInt(sender.NaturalVideoHeight);
								var objWidth = parseInt(sender.NaturalVideoWidth);
								var calcHeight = 1 / (objWidth / 715);
								objHeight = Math.floor(objHeight * calcHeight);
								objHeight = objHeight.toString();
								var $obj=$('#playerObj');
								$('#movieWrapper').css('height',objHeight+'px');
							    $obj.attr('height',objHeight);
							    $obj.attr('width','715');
							    $('div#silverlightControlHost').animate({'height' : objHeight + 'px'}, 500);
							}					
					    	var intHandle=null;
					    	
					    	var checkLoaded = function() {
								$('#playerObj').each(function(){
									if(this.Content && this.Content.Page) {
										videoPlayerLoaded(this.Content.Page);
										clearInterval(intHandle);
									}
								});
							}
							intHandle=setInterval(checkLoaded,1000);
							
							//send information about the movie to be logged in vod_stream_log
							var streamInfo = function() {
								$("#playerObj").each(function(){
									streamPosition = Math.round(this.Content.Page.Position);
									playerState = this.Content.Page.State;
									$.post("/COM/tlavideo/vod/VodInformation.cfc?method=sendDataToDB",
									{
										hotmovies_id: movieID,
										stream_position: streamPosition,
										player_state: playerState,
										player_type: "silverlight",
										player_screen: "normal"
									});
								});
							}
							var vodInfo = function() {
								var handleMinutes=function(minutes){
									minutes = minutes.replace(',','');
				                    minutes = parseInt(minutes);
									if (minutes < 4) {
										min = 0;
										$('form#player-speed, #minutes-warning').remove();
										if (minutes === 0) { min = 0; } else { min = 3; }
										var text = '<p id="minutes-warning" style="color: #c00;"><span style="font-weight: bold">';
										text += 'Warning:</span> You have less than ' + min + ' minutes remaining. ';
										text += '<a href="/vod/minutes.cfm" style="color:#c00;">Buy more</a></p>';
										$('table.pricing').after(text);
									}
								};
								if ($('span#currentVODMinutes').length > 0)	{
									handleMinutes($('span#currentVODMinutes').html());
								} else {
									$.ajax({
			                              type: "GET",
			                              data: {ts:new Date().getTime()},
			                              url: "../ajax/ajax_getVodMinutes.cfm",
			                              dataType: "xml",
			                              success: function(xml) {
			                                   $(xml).find('minutes').each(function(){
			                                		handleMinutes($.trim($(this).text()));
			                                   });
			                              }
			                        });
								}
							}
							var streamLog = setInterval(streamInfo, 15000);
							var vodMinutesStream = setInterval(vodInfo, 60000);
		
					  }
					});
					
					$('#lside').fadeOut('fast');
					$('table.pricing, div.alertBody').css('display', 'none');
					$('.vod-thumb').css('margin', '5px');
					$('#details').animate({paddingLeft : 0}, 2000);
					$('#rside').animate({width: 715}, 2000);
			
		}
		
		var makePlayer=function(start, movieID){
			var popupScenes = "";
			var counter = 0;
			$('div.vod-thumb a').each(function(){
				if (counter%7 === 0 || counter === 0) {
					popupScenes += "<div style='margin: 0 auto'>";
					popupScenes += $(this).html();
				} else if (counter%7 === 0 && counter != 1){
					popupScenes += "</div><div style='margin: 0 auto'>";
					popupScenes += $(this).html();
				} else {
					popupScenes += $(this).html();
				}
				counter++;
			});
			
			$('.upsells').after('<div id="sceneBuilder" style="display: none;"></div>');
			$('#sceneBuilder').html(popupScenes);
			var playerType = $.trim($('li.player_type').text());
			if (playerType === 'throwback') {
				legacyPlayer(start, movieID);
			} else if (playerType === 'popup'){
				popupPlayer(start, movieID);
			} else {
				standardPlayer(start,movieID);
			}
			
		}
		
		var addGoFragment =function(url,fragment){
			var loginParts=url.split("&");
			var keyval;
			for(var i=0;i<loginParts.length;i++){
				keyval=loginParts[i].split('=');
				if(keyval[0]==='go'){
					loginParts[i]='go=' + 
						keyval[1] + 
						escape('#' + fragment);
					break;
				}
			}
			return loginParts.join('&');
		};
		
		$("#vodMetaData .minutes").each(function(){
			$("#dynaUserMinutes").html("You have " + $(this).text() + " minutes <br /><a href='/vod/minutes.cfm'>Buy more</a>");
		});
		
		$("#activeRentalCacheSupportedMarkup").each(function(){
			$(".SR,.KR").find(".watch").html($(this).html());
		});
		
		var canStream=function(){
			var mins=0;
			$("#vodMetaData .minutes").each(function(){
				mins = parseInt($.trim($(this).text()));
			});
			return (
				//can watch with minutes
				(mins > 0 && $("#watchBtnContainer").length>0)
				|| 
				//has rental
				($("#activeRentalCacheSupportedMarkup").length>0 && 
				$(".SR .watch,.KR .watch").length>0)
			); 
		};
		
		//watch a streaming movie
		$('#watchBtnContainer a, div#scenes a, td.watch a[href="#watch"]').click(function(event){
			var start = '';
			var movieID = '';
			if($(this).children('img').attr('id')) {
				movieID = $(this).children('img').attr('id');
				movieID = movieID.split('_');
				start = movieID.length > 2 ? movieID[2] : 0;
				movieID = movieID[1];
			} else {
				movieID = $(this).children('img').attr('class');
				movieID = movieID.split('_');
				start = movieID[1];
				movieID = movieID[0];
			} 
			
			if(!globalUser.customer) {
				window.location=addGoFragment(
					$('#headerLoginLink').attr('href'),
					"watch," + String(start));
				return false;
			} else if (canStream()){
				event.preventDefault();
				if ($('#playerObj').length + $(this).parents('.vod-thumb').length === 2) {
					var playerObj = document.getElementById('playerObj');
					playerObj.Content.Page.SeekPlayback(start);
					return true;
				}
				makePlayer(start,movieID);
				return false;
			} else {
				//user can't stream title. take them to buy it first
				return true;
			}
		});

		//user video preferences on product details pages for VOD
		
		if ($('body.details div.hidden')) {
			$('body.details div.hidden *').unbind();
			$('body.details div.hidden form#player-type').remove();
			var preferences = $('body.details div.hidden').html();
			$('table.pricing').after(preferences);
			$('body.details div.hidden').slice(1).css('display', 'block');
		}
		
		// also reload the video if someone changes speed while watching
		
		$('form#player-speed input').change(function(target){
			var speed = $(this).attr('value');
			$.post('/customer/player_speed.cfm?speed=' + speed);
			var playerObj = document.getElementById('playerObj');
			if (playerObj) {
				start = playerObj.Content.Page.Position;
				var movieID = $('div#scenes a').children('img').attr('class').split('_')[0];
				makePlayer(start,movieID);
				return false;
			}
		});
		
		
		
		//in user account click 'edit' in order to alter account information
		
		 	var editableFormHandler = function() {
		 		$(this).addClass('accountDataUneditableEnabled');
		 		$(this).attr('readonly', 'readonly');
    			var elementID = $(this).attr('id');
    			var elementEditor = elementID + 'edit';
    			var elementSelector = '#' + elementID;
    			var elementEditorSelector = '#' + elementEditor;
    			var accountEditButton = "<span class='accountDataEdit'><a id='" + elementEditor + "'>Edit</a></span>";
    			var editClickHandler = function() {
    				$(elementSelector).attr('readonly', '');
    				$(elementSelector).removeClass('accountDataUneditableEnabled');
    				$(elementSelector).focus();
    				$(this).hide();
    			}
    			$(this).after(accountEditButton);
    			$(elementEditorSelector).click(editClickHandler);
    			$(this).bind('blur', function(){
    				$(this).addClass('accountDataUneditableEnabled');
    				$(elementEditorSelector).click(editClickHandler);
    				$(elementEditorSelector).show();
    			});
			}
			
			$('input.accountDataUneditable').each(editableFormHandler);
		//password functionality hides form fields	
			var editablePasswordHandler = function() {
				var password1 = $('input#password1');
				var password2 = $('input#password2');
				var passwordLabel = $('label[for="password1"]');
				var passwordContainer = $('div#passwordContainer');
				var holdingText = "<span class='passwordHoldingText'>***********************</span>";
				$(passwordLabel).html('Password');
				$(password1).hide();
				$(passwordLabel).after(holdingText);
				$('span.fine-print').hide();
				$(password1).after("<span class='accountDataEdit' id='passwordEditTrigger'><a>Edit</a></span>");
				$(password2).parent().hide();
				$('span#passwordEditTrigger a').click(function(){
					$('div#passwordContainer span').hide();
					$(passwordLabel).html('New Password');
					$(password2).parent().show();
					$(password1).show();
					$(password1).removeClass('accountDataUneditableEnabled').css('color','#000000');
					$('span.fine-print').show();
					$(password1).val('');
					$(this).hide();
				});
			}
			$('div#passwordContainer').each(editablePasswordHandler);
			
			
		//in new user signup first and last name mirror input from above on keyup
		
		var billingFirst = false;
		var billingLast = false;
		
		$('#a1_fname').blur(function(){
			if ($('#a1_fname').val()) {
				billingFirst = true;
			}
		});
		$('#a1_lname').blur(function(){
			if ($('#a1_lname').val()) {
				billingLast = true;
			}
		});
		$('#fname').keyup(function() {
			if (billingFirst != true) {
    		var keyDownValue = $('#fname').val();
    		$('#a1_fname').val(keyDownValue);
			}
		});
		$('#fname').blur(function() {
			if (billingFirst != true) {
				var keyDownValue = $('#fname').val();
				$('#a1_fname').val(keyDownValue);
			}
		});
		$('#lname').keyup(function() {
			if (billingLast != true) {
				var keyDownValue = $('#lname').val();
				$('#a1_lname').val(keyDownValue);
			}
		});
		$('#lname').blur(function() {
			if (billingLast != true) {
				var keyDownValue = $('#lname').val();
				$('#a1_lname').val(keyDownValue);
			}
		});
		
	//remove value from search field when focused on
		
	var searchText = 'Title, Director, Actor, Studio, Keyword...';
	if ($('body.gaybase').length) {
		searchText = 'Title, Director, Actor, Author, Studio, Keyword...';
	}
	
	$('input#search-input').attr('value', searchText);
		
	$('input#search-input').focus(function() {
		$(this).attr('value','');
		$(this).css('font-style', 'normal');
	});
	
	$('input#search-input').blur(function(){
		if ($(this).attr('value') == '') {
			$(this).attr('value', searchText)
		}
	});
	$('input#search-button').click(function(event){
		if ($('input#search-input').attr('value') == searchText || '') {
			event.preventDefault();
			return false;
		} else if (($('input#search-input').attr('value')).indexOf('...') == 39 || 47) {
			event.preventDefault();
			var currText = $('input#search-input').attr('value');
			currText = currText.replace('Title, Director, Actor, Author, Studio, Keyword...','');
			currText = currText.replace('Title, Director, Actor, Studio, Keyword...','');
			$('input#search-input').attr('value',currText);
			$('div#tla-search form').submit();
		} 
		$(this).parent().submit();
	}
	
	);
		// When you check the checkbox to remove yourself from email lists all checkmarks get removed
		$('input#nomail').change(function() {
			var noMailInput = $('input#nomail').attr('checked');
			if (noMailInput) {
				$(':checkbox').each(function(){
					if ($(this).parent().attr('class') == 'emailCheckbox') {
						$(this).attr('checked', '');
					}
				});
			}
		});
		
		// When you check a checkbox to receive email the 'receive no email' checkbox is cleared

		$('div.emailCheckbox input:checkbox').change(function(){
			var yesMailInput = $(this).attr('checked');
			if (yesMailInput) {
				$('input#nomail').attr('checked', '');
			}
		});
		
		//when you click on VOD Purchases in my account: if you have js link goes to ajaxified page if not you get a static page
		var myVodHref = $('li.vodHistory a').attr('href');
		if (myVodHref) {
			var newVodHref = myVodHref.replace('VODPurchasesNoJS', 'VOD');
			$('li.vodHistory a').attr('href', newVodHref);
		}
		
		// place tlagaycoukActive class on appropriate tab if adult or cinema VOD
		$('body#tlamoviescouk div#navigation li.tlamoviescouk, body#tlaondemandcouk div#navigation li.tlaondemandcouk').addClass('tlagaycoukActive');
		
		/* active input in form gets a border on focus */
		
		$('.activeForm input.required').each(function(){
			if ($(this).attr('value') === '' ) {
				$(this).attr('value','required');
			} else if ($(this).attr('value') === 'required') {
				return false;
			} else {
				$(this).css({
					'background':'#D7FFDC url(/Skins/graphics/70/elements/check.png) no-repeat right 50%',
					'color':'#222'
				});
			}
		});
		if ($('div#tlaReadyDisc div.user-error').length > 0) {
			$('.activeForm input.required').each(function(){
				if ($(this).attr('value') === 'required') {
					$(this).css({
						'background':'#FA8383 url(/Skins/graphics/70/elements/x.png) no-repeat right 50%',
						'color':'#222'
				})
				}
			});
		}
		$('.activeForm input').focus(function(){
			$(this).css('color','#222');
			if ($(this).attr('value') === 'required' || $(this).attr('value') === '') {
				$(this).attr('value','').css('border','1px solid #06c').prev().css('color','#06c');
			}
		});
		$('.activeForm input').blur(function(){
			$(this).css('border','1px solid #999').prev().css('color','#222');
				if ($(this).attr('value') === '' || $(this).attr('value') === 'required') {
					$(this).css('background','#fff').css('color','#aaa');
					if ($(this).hasClass('required')) {
						$(this).attr('value','required');
					}
				} else {
					$(this).css({
						'background':'#D7FFDC url(/Skins/graphics/70/elements/check.png) no-repeat right 50%',
						'color':'#222'
							});	
				}
		});

		$('.activeForm input[type="checkbox"]').unbind();
		
		var submitListener = function() {
				$('.activeForm input[type="submit"]').click(function(event){
				event.preventDefault();
				$('.activeForm input').each(function(){
					if ($(this).attr('value') === 'required') {
						$(this).attr('value','');
					}
				});
				$('.activeForm').submit();
			});
		}

		var showExplicit = function(event) {
			if ($(event.target).attr('value') === '0') {
				$(event.target).attr('value','1');
				$('.activeForm .hidden').fadeIn();	
			} else {
				$(event.target).attr('value','0');
				$('.activeForm .hidden').fadeOut();
			}
			submitListener();
		}
		if ($('.activeForm input.explicit:checked').length > 0) {
			var event = {'target': $('.activeForm input.explicit')}
			showExplicit(event);
		}
		$('.activeForm input.explicit').change(function(event){
			showExplicit(event);
		});
		
		submitListener();
		$('.activeForm input[type="submit"]').attr('value','submit');
		
		
		$('#displayPPMScenes').click(function() {
			$('#iPodScenes').toggle();
			$('#PPMScenes').toggle();
			return false;
		});
		
		$('#displayIPodScenes').click(function() {
			$('#PPMScenes').toggle();
			$('#iPodScenes').toggle();
			return false;
		});
		
		$('#iPodSceneStockPriceLink').click(function() {
			$.tlavideo.selectWindowTab($("ul.window-tabs a.scenes"));
			$('#PPMScenes').hide();
			$('#iPodScenes').show();
			return false;
		});
		
		$("a.removeCustFavorite").click(function(){
			var custVODFaveProdID = $(this).attr('id');

			$.ajax({
				type: "POST",
				url: "../ajax/removeCustVODFavorite.cfm?ts=" + new Date().getTime() + "&id=" + custVODFaveProdID,
				complete: function() {
					$('#product_' + custVODFaveProdID).html('deleted');
				}
			});
		});
		
		$.tlavideo.siteTabs().marquee().vodScenes().windowTabs().suckerFish().rawBottom().polls().bigForm().hideRefineSearch().formAutoFocus();
		compactForms($('form'));
		syncToUser();
		var newOverlay = new PPMOverlay;
		newOverlay.init();
		lsideDropDowns();
		if ($('body.raw-portal').length) {
			$slide = $('div.models img:first');
			var rndNum = Math.floor(Math.random() * $slide.siblings().length);
			var $random = $slide.siblings().eq(rndNum);
			$random.addClass('active');
			$('body.raw-portal').find('div.models img').css('display', 'block');
			var play = setInterval( "slideShow($slide)", 5000 );
			$('div.compact label span').show();
		}
		stateProvinceDisplay();

		// Update Minutes Only-If User is Logged In
		if (globalUser.customer) { 
			$("#vodMinuteBalance").each(function(){
				window.setInterval(function(){
					$("#vodMinuteBalance").each(loadUserContent);
				},60000);
			});
		}
		
		// Click event handlers for adult links on new portal page
		$('.adultVerifyLinkGA').click(function(){
			adultVerifyLightbox($(this).attr('href'),0);
			return false;
		});
		$('.adultVerifyLinkSA').click(function(){
			adultVerifyLightbox($(this).attr('href'),1);
			return false;
		});
		
		if(document.cookie.indexOf('ADULT_PASS=')>=0){
			$('div#adultVerifyContainer, div#overlay').hide();
		}
		
		$('a#adultVerifyContinue').click(function() {
			document.cookie="ADULT_PASS=1; path=/";
			$('div#adultVerifyContainer, div#overlay').hide();
			return false;
		});

		// Trailer banner for the VOD Gay page begins
			$('#VODTrailerBanner').bind('mouseover',function(){
				var trailerContent = $(this).find('.trailerBannerContent');
				if (trailerContent.width() == 159) {
					trailerContent.animate({width:761},750,function(){
						trailerContent.find('.trailerWrapper').html('<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="247" height="205" id="viddler_9b1879fa"><param name="flashvars" value="autoplay=t&wmode=transparent" /><param name="movie" value="http://www.viddler.com/simple/9b1879fa/" /><param name="allowScriptAccess" value="always" /><param name="allowFullScreen" value="true" /><embed src="http://www.viddler.com/simple/9b1879fa/" width="247" height="205" type="application/x-shockwave-flash" allowScriptAccess="always" flashvars="autoplay=t&wmode=transparent" allowFullScreen="true" name="viddler_9b1879fa" ></embed></object>');
						trailerContent.find('.trailerBannerClose').show();
					});
					$('.trailerBanner').fadeOut(750);
				}
			});
			$('.trailerBannerClose').click(function(){
				$('#VODTrailerBanner .trailerBannerContent .trailerWrapper').empty();
				$('#VODTrailerBanner .trailerBannerContent').animate({width:159},750);
				$(this).hide();
				$('.trailerBanner').fadeIn(750);
				return false;
			});
		// Trailer banner for the VOD Gay page ends
		
		$('.lp_trailerBanner a').click(function(){
			var banner = $(this).parent();
			banner.toggleClass('lp_trailerBannerOpen');
			lpTrailerBanner(banner.get(0),banner.hasClass('lp_trailerBannerOpen'));
			return false;
		});
		
		// Portal cycle code
		$('.photolist').each(function(i){
			var photoLabel = $(this).attr('id').split('-')[1];
			var photoList = $(this).val().split(',');
			var photoContainer = $('#photo-'+photoLabel+' a');
			for (var i = 1; i < photoList.length; i++) {
				photoContainer.append('<img src="'+photoList[i]+'" width="237" height="127" border="0" alt="" style="display:none;" />');
			}
		});
		
		$.tlavideo.trackFederatedLinks('body');
		
		$('.imgTop-left a img:eq(2)').load(function() {
			$('.imgTop-left a').cycle({	fx:'fade',timeout:5000,random:0,delay:-4000});
		});			
		$('.imgTop-right a img:eq(2)').load(function() {
			$('.imgTop-right a').cycle({	fx:'fade',timeout:6200,random:0,delay:-5000});
		});			
		$('.imgBtm-left a img:eq(2)').load(function() {
			$('.imgBtm-left a').cycle({	fx:'fade',timeout:6500,random:0,delay:-4000});
		});			
		$('.imgBtm-center a img:eq(2)').load(function() {
			$('.imgBtm-center a').cycle({	fx:'fade',timeout:5800,random:0,delay:-2000});
		});			
		$('.imgBtm-right a img:eq(2)').load(function() {
			$('.imgBtm-right a').cycle({	fx:'fade',timeout:5500,random:0,delay:-1000});
		});
		
		/* ie6 dotted outline fix */
		/**************************/
			
		$('a, input[type="radio"]').click(function(){
			this.blur();
		});
				
		// for the movie trailers on the details page | Yay! it works in IE again!
		$('#openTrailerLink').click(function(){
			$(document.body).append('<div id="trailerContainer2" class="lightbox"><a href="javascript:void(0);" class="lightboxClose" title="Close Window">close window</a></div>');
			if (!$('div#overlay').length) {
				$(document.body).append('<div id="overlay"></div>');
				$('div#overlay').width($(document).width()).height($(document).height());
			}
			var TrailerContent = $('#trailerContentWrapper').html();
			$.tlavideo.lightbox.open('trailerContainer2');
			$('#trailerContainer2').append(TrailerContent).center();
			$('#trailerContainer2 .lightboxClose').click(function(){
				$('#trailerContainer2, div#overlay').remove();
			});
			return false;
		});
		
		/* details premium title pop-up */
		/********************************/
		
		if ($('h3.premium-title a').length) {
			$('h3.premium-title a').click(function() {
				MyWindow = window.open('../details/premium-pop-up.cfm','MyWindow','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=no,width=550,height=300,left=35,top=35');
				return false;
			});
		}
		
		/* details box art back image functionality */
		/********************************************/
		
		if ($('div#box-art img.back').length) {
			$('span.mouseover-placeholder').html('Mouseover for more images').removeClass('mouseover-placeholder').addClass('mouseover');
			if ($('div.image-options a.enlarge').length && $('div.image-options span.mouseover').length) {
				$('div.image-options a.enlarge').addClass('float-right');
				$('div.image-options span.mouseover').addClass('float-left');
			}
			$('div#box-art img.front, div#details span.mouseover').hoverIntent({
				sensitivity: 1, // number = sensitivity threshold (must be 1 or higher)    
				interval: 100, // number = milliseconds for onMouseOver polling interval    
				over: showBackImage, // function = onMouseOver callback (REQUIRED)    
				timeout: 0, // number = milliseconds delay before onMouseOut    
				out: hideBackImage // function = onMouseOut callback (REQUIRED)    
			});
		}
		if ($('a.duplicated-link').length) {
			$('a.duplicated-link').click(function(){
				$('a.duplicated-link').attr('rel', 'box-art');
				$('a.duplicated-link').not(this).attr('rel', '');
			});
		}
		
		/* link to trailer */
		/*******************/
		
		$('div#details div.box-art div.trailer').show();
		
		/* ajax retrieval of guaranteed stock info */
		/********************************/
		
		ourSkus=$('div#details .pricing .warehouse').map(function(){return $(this).attr("title")}).get().join(',');
		if(ourSkus.length && globalServerDateTime.getHours()< 15 && 
		(new Date().getDate()) == globalServerDateTime.getDate()){
			var timeLeft = 14 - globalServerDateTime.getHours();
			if ( globalServerDateTime.getMinutes() == 0 ) {
				var minutes = "";
			} else {
			var minutes = " and " + (60 - globalServerDateTime.getMinutes()).toString() + " minutes";
			}
			switch (timeLeft) {
				case 1 : timeLeft += ' hour' + minutes;
				break;
				case 0 : timeLeft = (60 - globalServerDateTime.getMinutes()).toString() + " minutes";
				break;
				default : timeLeft += ' hours' + minutes;
				break;
			}
			$.get("/details/stock.cfc",
			{method: "guarantees", skus: ourSkus},
			function(data){
				var guaranteedSkus = data.split(",");
				if (guaranteedSkus != "") {
					var guaranteeCopy = "Ships today if ordered within the next ";
					for (var cur in guaranteedSkus) {
						$('div#details .pricing [title=' + guaranteedSkus[cur] + ']').parents('tr').after('<tr><td colspan="4" class="sameDayShipping"><span>Same Day Shipping: </span>' + guaranteeCopy +
						timeLeft +
						'. <a href="http://www.tlavideo.com/support/supportOption.cfm?supID=78"> Restrictions Apply</td><tr>');
					}
				}
			});
		}
		
		/* remove movie trailer on details page */
		/****************************************/
		
		$('div#details div#film-preview').remove();
		
		/* user reviews */
		/****************/
		
		// ajax call & display the review area, non javascript users get no luck
		$('div#details div#user-reviews div#review_area').css({'visibility': 'visible'});
		if ($('div#details div#user-reviews').length) {
			$.get("/COM/tlavideo/ajax/UserReviews.cfc?random=" + (Math.random() * Date.parse(new Date())),
			{
				method: "initUserReviews",
				sn: globalStoreName,
				g: globalGenre,
				v: globalView,
				id: globalProductID
			}, 
			function(response){
				$("div#review_area").html(response);
				$.tlavideo.userReviews();
			});
		}
		
		if(globalUser.customer){
			/* ajax call to add/remove vod favorite */
			/************************************/
			$("div#vodFavoriteText").each(function (){
				(new VODFavorite)
					.get(globalProductID);
			})
			/*ajax call to check for alerts on this product*/
			$("body.details div.alertMe").each(function(){
				$.get("../details/dspAlertMe.cfm",
					{id:globalProductID,v:globalView,sn:globalStoreName,g:globalGenre,ts:new Date().getTime()},
					function(data) {
						if(data){
							$("body.details div.alertMe").empty().append(data);
						}
					});
			});
		}
		
		if ($('a.remove-vod-fav').length) {
			$('a.remove-vod-fav').each(function(){
				$(this).attr('href', '#')
			});
			$('a.remove-vod-fav').click(function() {
				var favID = $(this).attr('id');
				$(this).addClass('ajax-remove');				
				$.ajax({
					type: 'GET',
					url: '/customer/cust_fave.cfm?random=' + (Math.random() * Date.parse(new Date())),
					data: 'a=delete&id=' + favID,
					success: function(data) {
						$('.ajax-remove').parent().parent().parent().hide();
					}
				});	
				return false;
			});
		}
		
		//start playing video if requested in url fragment
		if(window.location.hash && 
			globalUser.customer){
			$("#streamID").each(function(){
				var sent=false;
				var sendToHref=function(){
					sent=true;
					window.location=$(this).attr('href');
				}
				var hashParts=window.location.hash.split(",");
				if(hashParts[0].indexOf('watch')){
					if(canStream()){
						makePlayer(
							hashParts.length>1 ? hashParts[1] : 0,
							$.trim($(this).text()));
					} else {
						$("#watchBtnContainer a").each(sendToHref);
						if(!sent){
							$(".SR,.KR").find(".watch a:first").each(sendToHref);
						}
					}
				}
			})
		}
		
		//konami code
		if ($('body').hasClass('cult')) {
			function onKonamiCode(fn){
				var codes = (function(){
					var c = [38, 38, 40, 40, 37, 39, 37, 39, 66, 65];
					onKonamiCode.requireEnterKey && c.push(13);
					return c;
				})(), expecting = function(){
					expecting.codes = expecting.codes || Array.apply({}, codes);
					expecting.reset = function(){
					expecting.codes = null;
					};
					return expecting.codes;
				}, handler = function(e){
					if (expecting()[0] == (e || window.event).keyCode) {
						expecting().shift();
						if (!expecting().length) {
							expecting.reset();
							fn();
						}
					}
					else {
						expecting.reset();
					}
				};
				window.addEventListener ? window.addEventListener('keydown', handler, false) : document.attachEvent('onkeydown', handler);
			}
			
			onKonamiCode.requireEnterKey = false; // True/false
			onKonamiCode(function(){
			    //alert('konami code is working');
				$('a#konami').trigger('click');
			});
	}
	
	/*************
	 * vod prefs *
	 *************/
	
	if (('a.movieDownloadLink').length) {
		$('a.movieDownloadLink').click(function() {
			alert('Right click and select "Save As" to download this film.');
			return false;
		});
	}
	
	if (!$('#details-inner').length) {
		$('form#player-speed input').click(function(){
			updateRadioField("speed", $(this).val(), "player_Speed.cfm");
		});
		
		$('form#player-type input').click(function(){
			updateRadioField("player", $(this).val(), "player_prefs.cfm");
		});
	}
	
	if (('input#clearVodHistory').length) {
		$('input#clearVodHistory').click(function(){
			clearhistory();
		});
	}
	
	if ($('a.download-faq').length) {
		$('a.download-faq').click(function(){
			$('ul#download-faq').removeClass('hidden');
			return false;
		});
	}
	
	if ($('body.details span#thickbox-trailer').length){
		
		var trailerLink = $('body.details span#thickbox-trailer input#thickbox-trailer-link').attr('value');
		
		$('body.details span#thickbox-trailer').append('<h3 class="watch-trailer"><a href="'+trailerLink+'" class="thickbox">Watch Trailer</a></h3>');
	}
	
	if (navigator.userAgent.indexOf('Mac') != -1) {
		$(".wmdl-flag").click(function(){
			$this = $(this);
			wmdlFlag($this);
			return false;
		});
	}
		//fix search bar issues that are ie7 and ie6 only
		//change width if an option dropdown is present
		
		if ($.browser.version == '7.0' || $.browser.version == '6.0') {
				if ($('#tla-search select').length) {
					$('#tla-search').css('max-width','655px');
					$('.tla-advanced-search').css('width','100px');
				}
		}
	}); /* onloads end here */
	
	function showBackImage(){$('div#box-art img.front').animate({opacity: 0.0}, 1000);}
	function hideBackImage(){$('div#box-art img.front').animate({opacity: 1.0}, 1000);}
	
	function confirmUpdate() {
		if ($('#confirmBox.hidden').length) {
			$('#confirmBox').fadeIn('fast', function(){
				$(this).fadeOut(2000);
			});
		} else {
			$('#confirmBox p').fadeOut('fast');
			$('#confirmBox p').fadeIn('fast');
		}
	}
	
	function confirmDelete() {
		if ($('#vodhidehistory.hidden').length) {
			$('#vodhidehistory').fadeIn('fast').removeClass('hidden');
			$('#download-history, #rental-history, #ppm-history').html('<p><strong>No history avilable.</strong></p>');
		}
	}
	
	function clearhistory() {
		$.ajax({
			method: "get",
			url: "customer_vodhide.cfm",
			data: "clear=1" + "&timestamp=" + new Date().getTime(),
			success: confirmDelete()
			});
		}

	function updateRadioField(property, newValue, ajaxUrl) {
		$.ajax({
			method: "get",
			url: ajaxUrl,
			data: property + "=" + escape(newValue) + "&timestamp=" + new Date().getTime(),
			success: confirmUpdate()
		});
	}
	
	function lsideDropDowns() {
		if ($('.lside-dropDown').length) {
			$('.lside-dropDown').show();
			$('.lside-dropDown select').change(function(){
				selectionChange(this);
			});
			function selectionChange(selection){
				if (selection.value.length) {
					window.location = selection.value;
				}
			}
		
		}
	}
	
	/* form label over the input hide/show  */
	/* -------------------------------------*/
	/* change to a plugin using namespacing */
	/****************************************/
	
	function compactForms($region) {
		if ($region.length) { // if a form exists, apply the the jquery
					
			// add compact styling
			$region.find('.compact').addClass('compacted');
			
			// if the page loads with a value in a form field after the label hide the label and also
			// make the label disappear when you click it & focus on the next element
			$region.find('.compact label').each(function(){
				var getValue = $(this).next().val();
				if (getValue.length > 0) {
					$(this).hide();
				}
				$(this).click(function(){
					$(this).hide();
					$(this).next().focus();
				});
				
				// changed from focus to keypress so we can autofocus forms and still show the labels
				$(this).next().keypress(function(){
					$(this).prev().hide();
				});
				
				// show label on blur unless we've entered something
				$(this).next().blur(function() {
					var getValue = $(this).val();
					if (getValue.length > 0) {
						$(this).prev().hide();
					} else {
						$(this).prev().show();
					}
				});
			
			});
		
		}
		
		/* ie6 select z-index label over fix 
		 * creates an iframe which allows the label to show on top of the select box */
		/*****************************************************************************/
		
		var msie6 = $.browser.msie && /MSIE 6\.0/i.test(window.navigator.userAgent) && !/MSIE 7\.0/i.test(window.navigator.userAgent);
		
		if ($region.find('.compact select').length && msie6) {
			$region.find('.compact select').each(function() {
				if ($('form .compact select').prev('label').length) {
					var width = $(this).prev('label').width();
					var height = $(this).prev('label').height();
					$(this).parent().prepend('<iframe frameborder="0" scrolling="no" style="height:' + height + 'px; left:3px; width:' + width + 'px; position:absolute; top:3px;" />')
					$(this).change(function(){
						var getSelectedVal = $(this).children('option:selected').val();
						if (getSelectedVal.length > 1) {
							$(this).siblings('iframe').hide();
						}
						else {
							$(this).siblings('iframe').show();
						}
					});
				}
			});
		}
		
	}
	
	function loadUserContent(){
		var elementId=$(this).attr("id");
		var contentSource;
		var elementInit=function(){};
		switch(elementId){
			case "cart":
				contentSource="/head/CartInfoView.cfc";
				break;
			case "vodMinuteBalance":
				contentSource="/head/VODBalanceView.cfc";
				break;
			case "user-nav":
				contentSource="/head/UserInfoView.cfc";
				break;
			case "":
				contentSource="/head/VODBalanceView.cfc";
				break;
			default:
				contentSource="/unhandledUserView.cfm?id=" + elementId;
				break;
		}
		$.ajax({
			type: 'GET',
			url: contentSource,
			data: 'method=remoteDisplay&in=' + escape($("link[rel=canonical]").attr("href")),
			success: function(data) {
				$("#"+elementId).replaceWith(data);
				elementInit();
				$.tlavideo.trackFederatedLinks("#"+elementId);
			}
		});
	}

	function syncToUser()
	{
		if(globalUser.ispersonalized){
			//handle user-based view modules on new sessions
			$(".new-user").each(function(){
				if(!$(this).parent(".new-user").length){
					$(this).each(loadUserContent);
				}
			});
		} 
	}

	function lpTrailerBanner(e,tgl) {
		var banner = $(e);
		var controls = banner.parent().parent().find('div.ctrlpad');
		var nextbanner = banner.parent().next();
		var pauseEventPars = controls.find('a.play').attr('rel').split(',');
		var pauseRE = /(pause)+/i;
		// Open
		if (tgl) {
			if (pauseRE.test(controls.find('a.play img').attr('src'))) skipArticle(pauseEventPars[0],pauseEventPars[1],'stop');
			var trailerPath = banner.find('a').attr('rel');
			var detailsPath = banner.find('a').attr('href');
			banner.animate({height:420},750,function(){
				banner.css('background-position','right top');
				banner.append('<div class="lp_trailerContainer"></div>');
				banner.find('.lp_trailerContainer').html('<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="247" height="205"><param name="flashvars" value="autoplay=t&amp;wmode=transparent" /><param name="movie" value="http://www.viddler.com/simple/'+trailerPath+'/" /><param name="allowScriptAccess" value="always" /><param name="allowFullScreen" value="true" /><!--[if !IE]>--><object type="application/x-shockwave-flash" data="http://www.viddler.com/simple/'+trailerPath+'/" width="247" height="205"><!--<![endif]--><div class="alternative-content"><div class="background"></div><a href="http://www.adobe.com/go/getflashplayer" target="_blank"><strong>In order to view the trailer for this film, you need to have Adobe Flash Player version 9.0 or higher. Please download it now by clicking on this link.</strong><br/><br/><img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash Player" border="0" /></a></div><!--[if !IE]>--></object><!--<![endif]--></object>');
				banner.append('<a href="'+detailsPath+'" class="lp_trailerBannerMoreInfo">Click here for more info</a>');
			});
		// Close
		} else {
			skipArticle(pauseEventPars[0],pauseEventPars[1],'stop');
			banner.find('.lp_trailerContainer').remove();
			banner.find('lp_trailerBannerMoreInfo').remove();
			banner.animate({height:175},750,function(){
				$(this).css('background-position','left top');
			});
		}
	}

})(jQuery);

function adultVerifyLightbox(url,vagina) {
	var newURL = url.replace(/\?+/,'{}').replace(/\&+/g,"|");
	var bgimage = vagina?$('#imgSplashStraight').val():$('#imgSplashGay').val();
	$('#adultVerifyContainer').css('background-image','url('+bgimage+')');
	$('div#overlay').show().width($(document).width()).height($(document).height());
	$('#adultVerifyContainer').show().center();
	$('#adultVerifyContinue').attr('href','/adult_splash/pass.cfm?go='+newURL);
}

var articleInterval = new Array();
var articleIntervalCount = new Array();
var odBannerPos = 0;

function rotateArticle(seq) {
	var rowCount = 0;
	var curRow = 1;
	// figure out how many rows this SEQ has and set the display style
	while (document.getElementById("seq" + seq + "_row" + curRow)) {
		if (curRow == 1) {
			document.getElementById("seq" + seq + "_row" + curRow).style.display = "block";
		} else {
			document.getElementById("seq" + seq + "_row" + curRow).style.display = "none";
		}
		rowCount++;
		curRow++;
	}
	// set the rotation interval for this sequence
	articleInterval[seq] = window.setInterval("switchArticle(" + seq + "," + rowCount + ",'next')", 7000);
	articleIntervalCount[seq] = 0;
}

function switchArticle(seq,rowCount,action) {
	var curVisible = 0;
	var nextVisible = 0;
	// figure out which row is currently visible
	for (i=1; i <= rowCount; i++) {
		if (document.getElementById("seq" + seq + "_row" + i).style.display == "block") {
			curVisible = i;
			break;
		}
	}
	// based on current visible article, find the next article in the list to show
	if (action == 'next') {
		if (curVisible < rowCount) {
			nextVisible = curVisible + 1;
		} else if (curVisible == rowCount) {
			nextVisible = 1;
		}
	} else {
		if (curVisible <= rowCount && curVisible > 1) {
			nextVisible = curVisible - 1;
		} else if (curVisible == 1) {
			nextVisible = rowCount;
		}
	}
	// switch the display parameter on current and next visible articles
	document.getElementById("seq" + seq + "_row" + curVisible).style.display = "none";
	document.getElementById("seq" + seq + "_row" + nextVisible).style.display = "block";
	articleIntervalCount[seq]++;
	if (articleIntervalCount[seq] > 41) {
		skipArticle(seq,rowCount,'stop');
	}
}

function skipArticle(seq,rowCount,action) {
	if (action == 'next' || action == 'prev') {
		window.clearInterval(articleInterval[seq]);
		switchArticle(seq,rowCount,action);
		document.images['stopArticle' + seq].src = '../skins/graphics/icon_play.gif';
		//articleInterval[seq] = window.setInterval("switchArticle(" + seq + "," + rowCount + ",'next')", 7000);
		articleInterval[seq] = 0;
	} else if (action == 'stop') {
		if (articleInterval[seq]) {
			window.clearInterval(articleInterval[seq]);
			articleInterval[seq] = 0;
			document.images['stopArticle' + seq].src = '../skins/graphics/icon_play.gif';
		} else {
			articleInterval[seq] = window.setInterval("switchArticle(" + seq + "," + rowCount + ",'next')", 7000);
			articleIntervalCount[seq] = 0;
			document.images['stopArticle' + seq].src = '../skins/graphics/icon_pause.gif';
		}
	}
	return false;
}

function ondemandBannerSkip(d) {
	if (odBanner.length > 1) {
		var objBanner = $("#header-banner h2:eq(0) img:eq(0)");
		var objBannerLink = objBanner.parent();
		var i = 0;
		if (d) {
			if (eval(odBannerPos+1) == odBanner.length) {
				odBannerPos = 0;
			} else {
				odBannerPos++;
			}
		} else {
			if (odBannerPos == 0) {
				odBannerPos = eval(odBanner.length - 1);
			} else {
				odBannerPos--;
			}
		}
		if (odBanner && odBanner[odBannerPos]) {
			objBanner.attr("src",(d)?odBanner[odBannerPos].imgpath:odBanner[odBannerPos].imgpath);
			objBannerLink.attr("href",odBanner[odBannerPos].link);
		}
	}
}

function viewGallery(gid) {
	$.tlavideo.selectWindowTab($("ul.window-tabs a.image-gallery"));
}
//the following dsp_gallery function has been deprecated and is not recommended, please use viewGallery() instead
function dsp_gallery(gid) {
	viewGallery(gid);
}

// legacy functions
function replaceText(el, text) {
	if (el != null) {
		clearText(el);
		var newNode = document.createTextNode(text);
		el.appendChild(newNode);
	}
}

function clearText(el) {
	if (el != null) {
		if (el.childNodes) {
			childLength = el.childNodes.length;
			for (var i = 0; i < childLength; i++) {
				el.removeChild(el.firstChild);
			}
		}
	}
}

function getText(el) {
	var text = "";
	if (el != null) {
		if (el.childNodes) {
			for (var i = 0; i < el.childNodes.length; i++) {
				var childNode = el.childNodes[i];
				if (childNode.nodeValue != null) {
					text = text + childNode.nodeValue;
				}
			}
		}
	}
	return text;
}

function RTrim(str) {
	while(str.charAt((str.length -1))==" "){
		str = str.substring(0,str.length-1);
	}
	return str;
}

function LTrim(str){
	while(str.charAt(0)==" "){
		str = str.replace(str.charAt(0),"");
	}
	return str;
}

function Trim(str){
	str = LTrim(str);
	return RTrim(str);
}

function addLoadEvent(func) {
   var oldonload = window.onload;
   if (typeof window.onload != 'function') {
       window.onload = func;
   }
   else {
       window.onload = function() {
           oldonload();
           func();
       }
   }
}

function VODFavorite() {

    this.add = function(prodID) {
		$.ajax({
			type: "GET",
			url: "../ajax/ajax_VODFavorite.cfm",
			data: {a:"add",pid:prodID,ts:new Date().getTime()},
			complete: function(request) {
				var vodFaveLink = new VODFavorite;
				vodFaveLink.get(prodID);
			}
		});
    }

    this.get = function(prodID) {
        // Make sure the passed var is a number
		$.ajax({
			type: "GET",
			url: "../ajax/ajax_VODFavorite.cfm",
			data: {a:"view",pid:prodID,ts:new Date().getTime()},
			complete: function(request) {
				var XMLTableOutput = $(request.responseXML);
				var listFave = XMLTableOutput.find("favelist");
				var prodid = $.trim(XMLTableOutput.find("prodid:eq(0)").text());
				var isfave = $.trim(XMLTableOutput.find("isfave:eq(0)").text());
				// if not already a fave, show "add" link. If already a link, display "watch" message
				$('#vodFavoriteText').empty()
				if (isfave != 0) {
					$('#vodFavoriteText').append('<a href="javascript:void(0);"><img src="../skins/graphics/btns/remove.gif" border="0" alt="" /></a>');
					$('#vodFavoriteText').append('<a href="/customer/VOD.cfm?accountTab=VODFavorites" class="favorites">View Your Current VOD Favorites</a>');
				} else {
					$('#vodFavoriteText').append('<a href="javascript:void(0);"><img src="../skins/graphics/btns/favorites.gif" border="0" alt="" /></a>');
					$('#vodFavoriteText').append('<a href="/customer/VOD.cfm?accountTab=VODFavorites" class="favorites">View Your Current VOD Favorites</a>');
				}
				$('div#rside h2.title').addClass('minute-title');
				var vodFaveLink = new VODFavorite;
				if (isfave != 0) {
					$('#vodFavoriteText a:first-child').click(function() {
						vodFaveLink.remove(prodid);
					});
				} else {
					$('#vodFavoriteText a:first-child').click(function() {
						vodFaveLink.add(prodid);
					});
				}
			}
		});
    }

	this.remove = function(prodID) {
		$.ajax({
			type: "GET",
			url: "../ajax/ajax_VODFavorite.cfm",
			data: {a:"remove",pid:prodID,ts:new Date().getTime()},
			complete: function(request) {
				var vodFaveLink = new VODFavorite;
				vodFaveLink.get(prodID);
			}
		});
	}

}

function wmdlFlag($this) {
	
	// variables
	var $thisCell = $this.parent('td');
	var $parentRow = $thisCell.parent('tr');
	var parentRowWidth = $parentRow.width();
	var parentRowHeight = $parentRow.height();
	var thisHref = $this.attr('href');
	var thisTitle = $this.attr('title')
	if (thisTitle == 'wishlist') var wmdlMessageText = 'CONTINUE ADDING TO WISHLIST';
	else var wmdlMessageText = 'CONTINUE WITH PURCHASE';
	var wmdlMessage = ''
		+ 'Please note: TLA On-Demand Downloads can only be played on Windows systems.'
		+ '<br />Please see our <a href="/support/supportOption.cfm?v=4&sn=40&supID=43#faq17" '
		+ 'target="_blank" class="highlight">FAQ</a> for more details. '
		+ '<a href="#" class="highlight wmdlCancel">CANCEL</a> | '
		+ '<a href="'+ thisHref +'" class="highlight">'+ wmdlMessageText +'</a>'
	;
	var messageCSS = {
		height: parentRowHeight-5,
		opacity: 0,
		width: parentRowWidth-5
		
	};
	if (globalGenre == 1120) {
		$thisCell.append('<div class="wmdl-message">'+ wmdlMessage +'</div>');
		$thisCell.find('.wmdl-message').css(messageCSS).animate({opacity: 1}, 500);
	}
	
	//cancel click function
	$('.wmdlCancel').click(function(){
		$thisCell.find('.wmdl-message').remove();
		return false;
	});
}


function wmdlFlag($this) {
	
	// stock vs. vod - figure out where to put the message
	if ($('.vod-pricing').length) {
		$theContainer = $this.parent('div').parent('td');
	} else { 
		$theContainer = $this.parent('td');
	}
	
	// store the original href & title attributes
	var thisHref = $this.attr('href');
	var thisTitle = $this.attr('title')
	
	//final link text in message below
	
	if (thisTitle == 'wishlist') {
		wmdlMessageText = 'CONTINUE ADDING TO WISHLIST';
	} else {
		wmdlMessageText = 'CONTINUE WITH PURCHASE';
	}
	
	//beginining of message
	var wmdlMessage = ''
		+ 'Please note: TLA On-Demand Downloads can only be played on Windows systems - '
		+ 'please see our <a href="/support/supportOption.cfm?v=4&sn=40&supID=43#faq17" target="_blank" class="highlight">FAQ</a> for more details.'
		+ '<br /><a href="#" class="highlight wmdlCancel">CANCEL</a> | '
		+ '<a href="'+ thisHref +'" class="highlight">'+ wmdlMessageText +'</a>'
	;
	
	// get the container tr height, this is only a variable on the stock side
	var containerHeight = $theContainer.parent('tr').height();
	
	// jQuery helper CSS
	var wmdlCSS = {
		height : containerHeight,
		opacity : 0
		};
		
	//add the message
	
	if (globalGenre == 1120) {
	$theContainer.prepend('<div class="wmdl-message-bkg"></div><p class="wmdl-message">'+ wmdlMessage +'</p>');
	
	//fade it in
	$theContainer.find('.wmdl-message-bkg, .wmdl-message').css(wmdlCSS).animate({opacity:1}, 500);
	
	}
	//cancel click function
	$('.wmdlCancel').click(function(){
		$theContainer.find('.wmdl-message-bkg, .wmdl-message').remove();
		return false;
	});
}

function PPMOverlay() {

	var self = this;

	// a fail-safe to keep a user from clicking rapidly and launching
	// numerous overlays.
	var toggled = 0;

	// init();
	// Check to see if an item with the class .PPMoverlayImage exists
	// (this class will only exist on VOD scene images where PPM
	// isn't available, and the user doesn't have an active rental.)
	// Assign click functions to all such links.
	// Create our overlays.
	this.init = function() {

		var overlayClass = $(".PPMoverlayLink");
		if ($(".PPMoverlayLink").length) {
			this.create();

			// on click, toggle between
			// showing/hiding our overlay.
			$(".PPMoverlayLink")
				.click( function(e) {

					// capture event, fix it for IE
					var event = self.fixEvent(e);

					var pdOffset = $("#details #rside #scenes").offset();
					var pdHeight = $("#details #rside #scenes").outerHeight();
					var ovOffset = $("#PPMoverlay").offset();
					var ovHeight = $("#PPMoverlay").outerHeight();

					var newTop = (event.pageY-pdOffset.top)-(ovHeight/2);
					if (newTop < 1) { newTop = 1; }
					else if ((event.pageY-pdOffset.top)+(ovHeight/2) > pdHeight) {
						newTop = pdHeight-ovHeight;
					}

					if (toggled == 0) {
						$("#PPMoverlay").css("top", newTop);
						$("#PPMoverlay").fadeIn("normal");
						toggled = 1;
					} else {
						$("#PPMoverlay").hide();
						toggled = 0;
					}

					return false;
				});
				
			$("ul.window-tabs li a").click( function() {
				var tabClass = $(this).attr('class');
				if (tabClass !== 'scenes') {
					$("#PPMoverlay").hide();
					toggled = 0;
				}
			});

		}
	}; // end init();


	// fixEvent();
	// apparently IE doesn't have a pageX or pageY
	// return proper values in this
	this.fixEvent = function(e) {
		if ( e.pageX == null && e.clientX != null ) {
      		var e = document.documentElement, b = document.body;
      		e.pageX = e.clientX + (e && e.scrollLeft || b.scrollLeft || 0);
      		e.pageY = e.clientY + (e && e.scrollTop || b.scrollTop || 0);
   		}
   		return e;
	} // end fixEvent();

	// create();
	// Specify the error message.
	// Generate our overlays.
	// Determine the size and placement of our target div ("#scenes")
	// Center the overlays in the div.
	this.create = function() {

		var parentDiv = $("#details #rside div#scenes");
		var error = "<p>Sorry, this title is not available for Pay-Per-Minute. To purchase a rental of this title, click the link above.</p>" +
					"<img src='../skins/graphics/icon_close.gif' alt='' />";
		$("<div id='PPMoverlay'>" + error + "</div>")
			.prependTo(parentDiv);

		$("#PPMoverlay")
			.click( function() {
				if (toggled == 1) {
					$(this).hide();
					toggled = 0;
				}
				return false;
			})
			.css("display", "none");


	}; // end create();

}

/** swap display thumbs in sidebar lists **/

function swapListImg(id,list,imgsrc) {
	var myListImg = $("#listImg_" + list);
	var myListImgLink = $("#listImgLink_" + list);
	myListImg.attr("src", imgsrc);
	myListImg.attr("tooltip", id);
	myListImgLink.attr("href", "../templates/catalog_details.cfm?id=" + id + "&v=" + globalView + "&g=" + globalGenre + "&sn=" + globalStoreName);
}

/** user review helper function **/

function showReviewForm(yes) {
	if (yes) {
		$("#reviewForm").show();
		$("p.review_invite").hide();
	} else {
		$("#reviewForm").removeClass("show");
		$("#reviewForm").hide();
	}
	return false;
}

/** 
 ** slide switch function - http://jonraasch.com/blog/a-simple-jquery-slideshow
 ** -----------------------------------------------------------------------------------
 ** requires slides to positioned absolutely on top of each other
 ** the .active slide needs to be set to a higher z-index than .active-last.
 ** the .active-last slide needs to be set to higher z-index than the slides themselves.
 **
 **/

function slideShow($slide) {
	var $active = $('div.models img.active');
    var $next = $active.next().length ? $active.next() : $slide;
    $active.addClass('last-active');
    $next.css({opacity: 0.0})
        .addClass('active')
        .animate({opacity: 1.0}, 1000, function() {
            $active.removeClass('active last-active');
       	});
}

function marqueeSlideShow() {
	var $activeArticle = $('div#marquee div.current div.active');
	var $nextArticle = $activeArticle.next('div.article-sequence-group');
	var $activeGroup = $('ul#marquee-group-name li.active');
	var $nextGroup = $activeGroup.next('li').length ? $activeGroup.next('li').children('a') : $('ul#marquee-group-name li:first a');
	var $activeNumber = $('div#marquee div.current div.lpage-article-swap span.active');
	var $nextNumber = $activeNumber.next('span');
	if ($nextArticle.length) {
		$activeArticle.addClass('last-active');
		$nextArticle.css({
			opacity: 0.0
		}).addClass('active').animate({
			opacity: 1.0
		}, 0, function(){
			$activeArticle.removeClass('active last-active');
		});
		$activeNumber.removeClass('active');
		$nextNumber.addClass('active');
	} else {
		$nextGroup.trigger('mouseenter');
		if (!$('div#marquee ul#marquee-group-name').children('li:only-child').length) {
			if ($('ul#marquee-group-name li:first').hasClass('active')) {
				$('div#marquee span.ul-corner').css('background', 'url(/skins/graphics/70/tlaraw-new/marquee/ul-corner-first.gif) 0 0 no-repeat');
			} else {
				$('div#marquee span.ul-corner').css('background', 'url(/skins/graphics/70/tlaraw-new/marquee/ul-corner.gif) 0 0 no-repeat');
			}
		}
	}
	
}

function isEmail (s) {
   return String(s).search (/^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\@[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/) != -1;
}
	
	
if (navigator.appVersion.indexOf('Mac') != -1) {
	$(".wmdl-flag").click(function(){
		$this = $(this);
		wmdlFlag($this);
		return false;
	});
}

function stateProvinceDisplay() {
	$(".countrySelect").each(function(){
		var $section=$(this).parent();
		// check onload
		stateProvinceCheck($section);
		// check onchange
		$('.countrySelect select').change(function(){
			stateProvinceCheck($section);
		});
	});
}

function hideAndClear($section){
	$section.find("input,select").val('');
	$section.hide();
}


function stateProvinceCheck($section){
	var countryId=$section.find('.countrySelect option:selected').val();
	
	if (countryId == '0') {
		$section.find('.stateSelect').show();
		hideAndClear($section.find('.provinceInput'));
	} else if (countryId == '1') {
		$section.find('.provinceInput').show();
		hideAndClear($section.find('.stateSelect'));
	} else {
		hideAndClear($section.find('.stateSelect,.provinceInput'));
	}

}
