(function($){

	$.extend({

		tlavideo: {

			/* Content begins here */

			updateVMB: function() {
				var objMinute = $("#vodMinuteBalance");
				if (!objMinute.length) return false;
				$.ajax({
					type: "GET",
					data: {ts:new Date().getTime()},
					url: "../ajax/ajax_getVodMinutes.cfm",
					dataType: "xml",
					complete: function(xml) {
						var minutes = $("minutes",xml.responseXML).text();
						if (minutes == "error") return false;
						objMinute.text(minutes+" VOD"+((minutes!=1)?" Minutes ":" Minute "));
					}
				});
			},

			/* 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($.cookies.get(pollId))
					{
						$.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
							});
							
							//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(){ /* onloads begin here */
			
		//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);
		
		//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);
			}
		});
		// scroll to anchors so that site-tools does not cover anchor tag
		
		var scrollToAnchors = function(event){
		event.preventDefault();
		var targetURL = this.href;
                var targetArray = targetURL.split("#");
                var targetHash = targetArray[1];
                var targetName = 'a[name="' + targetHash + '"]';
                var targetOffset = $(targetName).offset();
                var targetFinal = parseFloat(targetOffset.top);
                targetFinal -= 60;
                $('html, body').animate({scrollTop:targetFinal}, 1000);
		}
		
		// 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');
		
		$('a.scrollableLink, div.alphabet-index p.letters a, div.alphabet-index h3.section-heading a').click(scrollToAnchors);
		
		$('#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();
		$.tlavideo.updateVMB();
		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 ( ! $("#login-email","#login") || ! $("#login-password","#login") ) { 
			if ($("#vodMinuteBalance").length) window.setInterval($.tlavideo.updateVMB,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($.cookies.get("ADULT_PASS")){
			$('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').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($("#productID","#watchBtnContainer").text());
			})
			/*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;
			});
		}
		
		//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;
		});
	}
	
	$('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.appVersion.indexOf('Mac') != -1) {
		$(".wmdl-flag").click(function(){
			$this = $(this);
			wmdlFlag($this);
			return false;
		});
	}
		
	}); /* 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 syncToUser()
	{
		if(globalUser.ispersonalized){
			//handle user-based view modules on new sessions
			$(".new-user").each(function(){
				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;
				}
				if(!$(this).parent(".new-user").length){
					$.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 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 = XMLTableOutput.find("prodid:eq(0)").text();
				var isfave = 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>');
				} else {
					$('#vodFavoriteText').append('<a href="javascript:void(0);"><img src="../skins/graphics/btns/favorites.gif" border="0" alt="" /></a>');
				}
				$('div#rside h2.title').addClass('minute-title');
				var vodFaveLink = new VODFavorite;
				if (isfave != 0) {
					$('#vodFavoriteText a:last-child').click(function() {
						vodFaveLink.remove(prodid);
					});
				} else {
					$('#vodFavoriteText a:last-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
		
	};
	
	$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
	$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'));
	}

}