var $j = jQuery.noConflict();				// we namespace our jQuery to prevent conflicts with prototype
tbSearch = window.tbSearch || {};			// tbSearch contains all of the search autocomplete functionality
tbPromos = window.tbPromos || {};			// tbPromos contains all the promo block functionality
tbAddToCart = window.tbAddToCart || {};		// maintain state of add to cart
tbModal = window.tbModal || {};
FC_TBJS = window.FCTBJS || {};			
Brightcove = window.Brightcove || {};		// Brightcove contains all video functionality
tbBigDog = window.tbBigDog || {};				// functionality to handle all featured title functionality
ymal = window.ymal || {};						// you may also like
tbGrid = window.tbGrid || {};					// all the functionality for the grid view filters
tbCommon = window.tbCommon || {};				// functions that all modules will use
$j(document).ready(function() {

	tbCommon.isArray = function(obj) {if (obj.constructor.toString().indexOf("Array") == -1)	return false; else return true;	}
	tbCommon.getBaseUrl = function(){
		var location = window.location;
		var url = location.protocol + "//" + location.hostname + "/";
		return url;
	}
	
	/* Search Autocomplete */
	tbSearch.delay = 0.5;															// time delay in seconds for initiating ajax search
	tbSearch.minLength = 3;															// min string length before initiating ajax search
	tbSearch.header = "Most relevant matches shown. Click Search for more items.";	// header text in ajax search results drop down
	tbSearch.timeout = "";															// global timeout variable for ajax search drop down
	tbSearch.formatResult = function(result){
		var img = "";
        img = "<img src=\""+ result.Image + "\">";
        return "<div class=\"result\">" + img + "<div class=\"result-text\"><p class=\"name\">" + result.Title + "</p><p class=\"genres\"><strong>Genres: </strong>"+result.Genres+"</p><p class=\"actors\">"+result.Actors+"</p><a style='display:none' href='"+result.Url+"'></a></div></div>";
	}
	tbSearch.generateRequest = function(sQuery) {
		var storeId = $j('#search-store-id').val();
        return '?q=' + sQuery +'&storeId='+ storeId;
    };
	tbSearch.initiateQuery = function(path){
		$j.ajax({
			method:"get",
			url: path,
			dataType: "jsonp",
  			jsonp: 'callback',
			success: tbSearch.resultsHandler
		});
	}
	tbSearch.hideLoadingGraphic = function(){ $j('#myInput').css({ background: 'transparent'});}
	tbSearch.resultsHandler = function(results){
		var header = '<div class="yui-ac-hd">' + tbSearch.header + '</div>';
		var body = '<div class="yui-ac-bd"></div>';
		var footer = '<div class="yui-ac-ft"></div>';
		
		var html = '<div class="yui-ac-content yui-ac">' + header + body + footer + '</div>';
		$j('#myContainer').html(html);
		var items = $j('#myContainer .yui-ac-bd');
		for( i=0; i< results.ResultSet.totalResultsReturned; i++){
			items.append(tbSearch.formatResult(results.ResultSet.Result[i]));
		}
		if ( $j('#myContainer').not(':visible') ) { $j('#myContainer').show(); }
		tbSearch.hideLoadingGraphic();
	}
	tbSearch.search = function(){
		str = $j('#myInput').val();
		if (str.length >= tbSearch.minLength){
			tbSearch.showLoadingGraphic();
			var url = $j('#search-base-url').val() + "/searchautocomplete/ajax/suggest/";
			var query = tbSearch.generateRequest(str);
			var url = url + query;
			
			tbSearch.initiateQuery(url);
		}
	}
	tbSearch.showLoadingGraphic = function(){var url = $j('#search-skin-url').val() + 'images/al.gif';var background = 'transparent url('+url+') no-repeat 115px 3px';$j('#myInput').css({background: background});}
	
	
	/* Event handler for the search box input field */
	$j('#search_mini_form input#myInput').keyup(function(){
		clearTimeout(tbSearch.timeout);
		tbSearch.timeout = setTimeout( tbSearch.search, tbSearch.delay * 1000 );
	});
	
	/* event handler for hiding and showing initial text in the search box */
	$j('#myInput').focus(function(){
		$j(this).parent().parent().find('label').hide();
	});
	$j('#myInput').blur(function(){
		if( $j(this).val() == "" ) {
			$j(this).parent().parent().find('label').show();
		}
	});
	
	/* Event handler for the search results drop down mouse over / out */
	$j("#myContainer").mouseover(function(){
		clearTimeout(tbSearch.timeout);
	});
	$j('#myContainer').mouseout(function(){
		tbSearch.timeout = setTimeout(function(){ $j('#myContainer').hide() }, 1000);
	});
	
	/* Event handlers for the search results mouse over/out/click */
	$j('#myContainer .yui-ac-bd .result').live("mouseover", function(){
		$j(this).addClass('yui-ac-highlight');
	});
	$j('#myContainer .yui-ac-bd .result').live("mouseout", function(){
		$j(this).removeClass('yui-ac-highlight');
	});
	$j('#myContainer .yui-ac-bd .result').live("click", function(){
		var url = $j(this).find('a').attr('href');
		window.location.href = url;
	});
	
	/* From formatMenu.js */
	
	$j('#fox_tabs ul li a').click(function(){ 
		try {
			$j('#fox_tabs ul li').removeClass('active');
			$j(this).parent().addClass('active');
			var currentTab = $j(this).attr('href');
			$j('#fox_tabs div').hide();
			$j(currentTab).show();
			return false;
		} catch(e){
			//console.log(e);
		}
	});
			
	//Toggles plus/minus on product pages				
	$j(".catalog-product-view .dropbar h4.trigger").toggle(function(){
		$j(this).addClass("active");
		$j('.dropbar-container').slideDown('normal');
	}, function () {
		$j(this).removeClass("active");
		$j('.dropbar-container').slideUp('normal');	
	});
	// product format tabs, prevent clicking on the currently selected tab
	$j('ul.media-type li a.current').click(function(e){
		e.preventDefault();
	});
	// Truncates the product synopsis on the product detail page
   	$j("div#prod-details-desc").truncate( 250, {
   		chars: /\s/,
   		trail: [ " ( <a href='#' class='truncate_show'>more</a> . . . )", " ( . . . <a href='#' class='truncate_hide'>less</a> )" ]
   	});
	
	/* from menu.js */
	/* Search Bar label hide/show */
	$j('#myInput').focus(function(){$j(this).parent().parent().find('label').hide();});
	$j('#myInput').blur(function(){	if($j(this).val()=="") $j(this).parent().parent().find('label').show();});
	
	/* Video Search Bar label hide/show */
	$j("#vid-gridSearch").val($j("#vid-gridSearch").attr('title'));
	$j('#vid-gridSearch').focus(function(){this.value = $j(this).attr('title');if (this.value == $j(this).attr('title')) this.value = "";});
	$j('#vid-gridSearch').blur(function(){if(this.value == "" ) this.value = $j(this).attr('title');});
	
	/* Advanced Search Bar label hide/show */
	$j("#keyword").val($j("#keyword").attr('title'));
	$j('#keyword').focus(function(){this.value = $j(this).attr('title'); if (this.value == $j(this).attr('title')) this.value = "";});
	$j('#keyword').blur(function(){if(this.value == "" ) this.value = $j(this).attr('title');});
	$j('a.advanced-search-btn').click(function(e){e.preventDefault();if($j('div.advanced-search').is(':visible')){ $j('div.advanced-search').hide();} else {$j('div.advanced-search').slideDown();}});
  	$j("ul.sf-menu").superfish({ pathClass:'current' }); 
  	$j("div.scrollable").scrollable({ vertical:true,size: 5 }).mousewheel(); 
	$j('li.new-releases a.sf-with-ul, li.top-sellers a.sf-with-ul, li.genres a.sf-with-ul, li.franchises a.sf-with-ul').click(function(e){ e.preventDefault(); });
	
	
	/* from example.js */
	/* if we're on a product detail page */
	if($j('.product-img-box .ratings-block').length > 0){
		/* fetch the product detail ratings block */
		var url = $j("#fox-ratings-form-baseurl").val();
		var pid = $j("#fox-ratings-form-pid").val();
		url += "rating/product/prep/product_id/"+pid;
		$j.ajax({
			method:"get",
			url:url,
			dataType:"json",
			success:productDetailRatings
		});
	} 
	if($j('.catalog-product-view #fox-ratings-form-product').length > 0){
		/* fetch the product detail ratings block */
		var url = $j("#fox-ratings-bundle-baseurl").val();
		var pid = $j("#fox-ratings-bundle-pid").val();
		url += "rating/product/prep/product_id/"+pid;
		$j.ajax({
			method:"get",
			url:url,
			dataType:"json",
			success:bundleDetailRatings
		});
	} 
	
	function productDetailRatings(result){
		var res = writeRatings(result);
		$j('.product-img-box .ratings-block').append(res);
		if(result.no_login == 1){
			var txt = $j('.product-img-box .rate h4').text();
			$j('.product-img-box .rate h4').text("Log in to "+txt);
		}
		$j('.product-img-box .ratings-block').each(function(){
			$j(this).find('input.foxstar').rating({
				callback: function(value, link){
					submitRating(value, 'fox-ratings-form-pid', 'fox-ratings-form-baseurl', false);
				}
			});	
			$j("div.ratings-block").show();
		});
	}
	
	function bundleDetailRatings(result){
		var res = writeRatings(result);
		$j('#fox-ratings-form-product').append(res);
		$j('#fox-ratings-form-product').each(function(){
			$j(this).find('input.foxstar').rating({
				callback: function(value, link){
					submitRating(value, 'fox-ratings-bundle-pid', 'fox-ratings-bundle-baseurl', false);
				}
			});	
			$j("div.bundle-rating").show();
		});
	}
	
	function writeRatings(result){
		var res = "";
		var rating = Math.ceil(parseFloat(result.rating));
		var total = parseInt(result.total);
		var isLoggedIn;
		if (result.no_login == 1) {
			isLoggedIn = false;
		} else {
			isLoggedIn = true;
		}
		for(var i=1; i<=5; i++){
			res += "<input type='radio' value='"+i+"' name='product' class='foxstar'";
			if ( i == rating) res += " checked='checked' ";
			if (!isLoggedIn) res += " disabled='disabled' ";
			res +="/>";
		}
		res += "<div class='clear'><p>";
		res += rating + " of 5 (";
		res += total + " review";
		if (total != 1) res += "s";
		res += ")</p></div>";
		
		return res;
	}
	
	$j('.ratings-block, .bundle-rating').each(function(){
		var id = 'fox-ratings-form-pid';
		var isVideo = false;
		var baseUrl = 'fox-ratings-form-baseurl';
		if ($j(this).hasClass('bundle-rating')) {id='fox-ratings-bundle-pid'; baseUrl='fox-ratings-bundle-baseurl';}
		if ($j(this).hasClass('video-rating')) {isVideo=true;id='fox-ratings-form-bid';}
		$j(this).find('input.foxstar').rating({
			callback: function(value, link){
				submitRating(value, id, baseUrl, isVideo);
			}
		});	
		$j(this).show();
	});
	
	function submitRating(rating, id, baseUrl, isVideo){
		var path = 'rating/product/post/product_id/';
		if (isVideo) path = 'videorating/clip/post/clip_id/'
		var url = $j("#"+baseUrl).val() + path + $j("#"+id).val();
		var end = '/option_id/';
		if (isVideo) end = '/rating/';
		url += end+rating;
		$j.get(url, {}, 
			function(result){
				$j('.foxstar').rating('readOnly', true);
			}, "json");
	}
	
	/* Promos */
	tbPromos.HEIGHT = 184;
	tbPromos.WIDTH = 304;
	tbPromos.CONTRACTED_WIDTH = 150;
	tbPromos.CONTRACTED_HEIGHT = 184;
	tbPromos.EXPANDED_WIDTH = 610;
	tbPromos.EXPANDED_HEIGHT = 472;
	tbPromos.DURATION = 700;
	tbPromos.POSITION = 0;
	tbPromos.SMALL_POSITION = tbPromos.EXPANDED_HEIGHT - tbPromos.CONTRACTED_HEIGHT - 4;
	$j("div.promo .main a").click(function(e){ if ($j(this).attr("href") == "#") e.preventDefault();});
	$j("div.promo.expandable .main a").click(function(e){
		e.preventDefault();
		if ($j(this).parents("div.promo").hasClass("expanded") ) {
			return;
		}
		var parent = $j(this).parents('div.promo-bar');
		if ( $j(parent).find("div.promo.expanded").length > 0 ) {
			// if there's an already expanded promo, shrink it first, then expand the next one
			var expanded = $j(parent).find("div.promo.expanded .main a")
			tbPromos.contract(expanded, this);
		} else {
			tbPromos.expand(this);
		}
		
	});
	$j("div.promo.expandable div.close a").click(function(e){e.preventDefault();var node = $j(this).parents("div.promo.expanded").find(".main a");tbPromos.contract(node, null);});
	
	tbPromos.removeExpanded = function(expanded){$j(expanded).parents('div.promo').removeClass("expanded");	$j(expanded).parents('div.promo').siblings().removeClass("contracted");}
	
	tbPromos.contract = function(expanded, node){
		if ($j(expanded).siblings("div.site").length > 0) {
			$j(expanded).show().siblings("div.site").hide();
		}
		$j(expanded).syncAnimate($j(".promo .main a").not(expanded), {width:tbPromos.WIDTH}, {duration:tbPromos.DURATION, queue:false});
		var parent = $j(expanded).parents('div.promo');
		$j(parent).animate({top:0}, tbPromos.DURATION);
		if (node) {
			$j(expanded).animate({
				height: tbPromos.HEIGHT
			}, tbPromos.DURATION, function(){
				tbPromos.removeExpanded(expanded);
				tbPromos.expand(node);
				if ($j(expanded).find('span').length > 0) $j(expanded).find('span').show();
			});
		} else{
			$j(expanded).animate({
				height: tbPromos.HEIGHT
			}, tbPromos.DURATION, function(){
				tbPromos.removeExpanded(expanded);
				if ($j(expanded).find('span').length > 0) $j(expanded).find('span').show();
			});
			tbPromos.hideOverlay();
		} 
	}
	tbPromos.expand = function(node){
		$j('div.promo-bar').css({zIndex:1000});
		var parent = $j(node).parents("div.promo");
		if ($j(node).find('span').length > 0) $j(node).find('span').hide();
		$j(node).syncAnimate($j(".promo .main a").not(node), {width:tbPromos.EXPANDED_WIDTH}, {duration:tbPromos.DURATION, queue: false});
		
		$j(parent).animate({top: (tbPromos.SMALL_POSITION * -1)}, tbPromos.DURATION);
		$j(node).animate({height:tbPromos.EXPANDED_HEIGHT }, tbPromos.DURATION, function(){
			if ($j(node).siblings("div.site").length > 0) {
				$j(node).hide().siblings("div.site").show();
			}
		});
		$j(parent).addClass("expanded");
		$j(node).parents('div.promo').siblings().addClass("contracted");
		tbPromos.showOverlay();
	}
	
	tbPromos.showOverlay = function(){
		if (!($j.browser.msie && $j.browser.version.substr(0, 1) <= 7)) {
			if ($j("div.promo-overlay").length > 0) {
				$j("div.promo-overlay").show();
			}
			else {
				$j("div#main").prepend("<div class='promo-overlay'></div>");
				var height = $j('div#main').height();
				$j("div.promo-overlay").css({
					opacity: 0.5,
					height: height + "px"
				});
				$j("div.promo-overlay").show();
			}
		}
	}
	tbPromos.hideOverlay = function(){$j("div.promo-overlay").hide();}
	
	
	/* From featuredTitles.js */
	$j('div.videoOverlay a').live("click", function(e){
		e.preventDefault();
		var parentDiv = $j(this).parents('div.videoOverlay');
		// get the video id to load
		var videoId = parentDiv.attr('id').split("-")[1];
		var videoUrl = parentDiv.find("input#videoUrl").val();
		var emailUrl = parentDiv.find("input#emailUrl").val();
		// hide the overlay
		$j(this).hide();
		
		// hide the overlay bar
		$j(this).parents("div.content").find(".info-overlay").hide();
	    $j(document).stopTime("transition");
		$j("#feature").galleryView.pause();
	    
		var playerId = "player-"+videoId;
		
		flashembed(playerId, {src: videoUrl, width:598,	height:325,	wmode:'transparent', bgcolor:'#000000', id:'FoxConnect'}, {playerID: "41122650001", videoID:videoId, width:598, height:325, emailUrl:emailUrl});
		$j("#"+playerId).show();
		$j('<a href="#" class="brightcove-close">[x]</a>').prependTo($j("#"+playerId));
		$j("#"+playerId+" a.brightcove-close").click(function(e){
			e.preventDefault();
			Brightcove.stop();
			Brightcove.finished();
		});
		$j("#"+playerId).hover(function(){
			$j(this).find("a.brightcove-close").show();
		}, function(){
			$j(this).find("a.brightcove-close").hide();
		});
	});
	
	/* from basic.js */
	tbModal.timeout;
	tbModal.lastOpenedProduct = "";
	tbModal.coords = ["",""];
	$j('.catalog-listing .product-image').hoverIntent(function(){$j(this).find('.quickview').fadeIn();},function(){setTimeout(function(){},500);$j(this).find('.quickview').fadeOut('fast');});
	$j('.scrollable-tabs .items .product-image').hoverIntent(function(){ $j(this).find('.quickview').fadeIn();},function(){setTimeout(function(){},500);$j(this).find('.quickview').fadeOut('fast');});
	$j('.ymal-image').hoverIntent(function(){ 
		$j(this).find('.quickview').fadeIn();
		}, 
		function(){ 
		setTimeout(function(){},500); 
		$j(this).find('.quickview').fadeOut('fast');
		});
  	$j('.ymal-image .product-image').hoverIntent(
		function(){ $j(this).find('.quickview').fadeIn();}, 
		function(){ setTimeout(function(){},500); 
			$j(this).find('.quickview').fadeOut('fast');
		});
	
	$j('.quickview a').live("click",function(e){
		e.preventDefault();
		if ($j(this).get(0) == $j(tbModal.lastOpenedProduct).get(0)) {$j("#modal").overlay({expose:'#f1f1f1', closeOnClick:false, api:true }).load();}
		else {
			tbModal.lastOpenedProduct = $j(this);
			tbModal.coords[0] = e.pageX;
			tbModal.coords[1] = e.pageY;
			var url = $j(this).attr("href");
			if(url.charAt(url.length-1) != "/"){ url+= "/"}
			url += "tbjs/1";
			$j.ajax({type:"GET",dataType:"json", url: url, success:function(resp){doModal(resp);}, error:function(resp){}});
		}
	});
	
	function doModal(response){
		var node = $j(tbModal.lastOpenedProduct).parents("td, div.listing-item, .ymal-image, .items .product-image");
		var title = response.product.name;
	    if (title.length > 50) title = title.substr(0, 46) + "...";
		$j("#quickview-title").html( title );
		if (response.product.format != false) title += " ("+response.product.format+")";
		$j("#quickview-price").html("$"+response.product.price);
		
		var img = node.find("a img");
		$j("#quickview-thumbnail").attr({src: img.attr("src"), alt: img.attr("alt")});
		$j("#quickview-addtocart a.addtocart").attr("href", response.product.addToCart);
		
		if (response.product.rating != ""){ $j("#quickview-rating").removeClass("pg").removeClass("g").removeClass("r").removeClass("pg-13").removeClass("ur").removeClass("nr").addClass(response.product.rating).text(response.product.rating).attr("title",response.product.rating); $j("#quickview-rating-container").show();} else {$j("#quickview-rating-container").hide();}
		if (response.product.actors != "") {$j("#quickview-actors").html(response.product.actors); $j("#quickview-actors-container").show();} else {$j("#quickview-actors-container").hide();}
		if (response.product.director != "") {$j("#quickview-directors").html(response.product.director);$j("#quickview-directors-container").show();} else {$j("#quickview-directors-container").hide();}
		if (response.product.genre != "") {$j("#quickview-genre").html(response.product.genre);$j("#quickview-genre-container").show();} else {$j("#quickview-genre-container").hide();}
		$j("#quickview-synopsis").html(response.product.synopsis);
		$j("#quickview-view").attr("href", response.product.url );
		
		var formats="", j=0;
		if ( !tbCommon.isArray(response.product.formats) ) {
			for (var k in response.product.formats) { if (j > 0) formats += "<li class='separator'>:</li>"; formats += "<li><a href='" + response.product.formats[k].url + "'>" + k + "</a></li>"; j++;}
			if ( j > 1) {$j("#quickview-formats").html(formats);$j('#also').show(); } else { $j('#also').hide();}
		} else { $j('#also').hide();}
		$j("#modal").overlay({ closeOnClick:false, expose:'#f1f1f1', api:true }).load();
	}
	
	FC_TBJS.isCartPage = false;
	FC_TBJS.TIMEOUT_VAL = 2500;
	FC_TBJS.timeout;
	function checkIsCartPage(){	if( window.location.toString().search('/checkout/cart/') != -1 ) {	FC_TBJS.isCartPage = true; }}
	function addToCartListeners(){
		$j('#product_addtocart_form').live("submit", function(e){
      		e.preventDefault(); // interrupt normal form submit
			var qty = $j("#qty").val();
			if (parseInt(qty) == 0 || qty == "") {qty = 1;$j("#qty").val(qty);} // check to see if the qty field is populated, set to default 1 if not
			ajaxcartsend("tbjs/1", "form", "");
    	});
		$j('#product_addtocart_form .add-to-cart-box a').live("click", function(e){e.preventDefault();$j('#product_addtocart_form').trigger("submit");});
	}
	function init(){checkIsCartPage();addToCartListeners();}
	init();
	
	/* from brightcove.js */
	Brightcove.index = 0;
	Brightcove.playlist = $j('#related-video a.brightcove');
	$j('#related-video .items div').eq(0).addClass("selected");
	$j('#related-video .items div').hover(function(){$j(this).addClass("hover");},function(){ $j(this).removeClass("hover");});
	
	Brightcove.click = function(e){
		e.preventDefault();
		var videoId = $j(this).attr('id').split("-")[1];
		var parent = $j(this).parent('div');
		var title = $j(this).text();
		var vid = parent.find('input.video-id').val();
		var rating = parent.find('input.video-rating').val();
		var count = parent.find('input.video-count').val();
		Brightcove.reloadInfo(title, vid, rating, count);
		Brightcove.load(videoId);
		$j("#related-video .items > div").removeClass("selected");
		$j(this).parents('.items > div').addClass("selected");
		Brightcove.index = Brightcove.playlist.index(this);
	}
	Brightcove.reloadPlayer = function(videoId){
		flashembed("player", 
			{
				src: $j('#fox-video-player').val(),
				wmode:'transparent',
				width:598,
				height:325,
				bgcolor: '#000000',
				id:'FoxConnect'
			},
			{
				playerID: "41122650001",		// this player should be in the magento admin for brightcove
				videoID: videoId,			// this is the video we're loading initially
				width:598,
				height:325,
				emailUrl:$j('#fox-video-email-url').val()
			} 
		);
	}
	// getMovie returns the object/embed for the swf itself
	Brightcove.getMovie = function(movieName){if (navigator.appName.indexOf("Microsoft") != -1) return window[movieName]; else return document[movieName];}
	Brightcove.getUrl = function(){var domain = window.location.protocol+"//"+window.location.hostname;var path = window.location.pathname; return domain+path;}
	Brightcove.load = function(videoId){try{ /*this.getMovie('FoxConnect').loadVideo(videoId);*/ Brightcove.reloadPlayer(videoId); } catch(e){}}  // calls function in flash file itself
	Brightcove.stop = function(){try {this.getMovie('FoxConnect').stop();} catch(e){}}					   // calls function in flash file itself
	Brightcove.incrementVideoCount = function(vid, isVideo){
		var url = $j("#search-base-url").val() + "video/index/views/vid/"+vid+"/is_video/"+isVideo;
		$j.ajax({ method:"get", url:url, success:function(res){}, error:function(msg){} });
	}
	Brightcove.nextVideo = function(){
		// this is what we'll call to load another video from our list
		Brightcove.index++;
		if(Brightcove.index < Brightcove.playlist.length) $j(Brightcove.playlist).eq(Brightcove.index).trigger('click');
	}
	Brightcove.finished = function(){
		Brightcove.incrementVideoCount($j("#fox-ratings-form-bid").val(), $j('#fox-video-page').val());
		$j(".featuredTitleVideo").empty().hide();
		$j("div.videoOverlay a").show();
		$j('#feature div.info-overlay').show();
		setTimeout(function(){$j("#feature img.nav-next").trigger("click");}, 500);
	}
	Brightcove.queue = function(brightcoveId, videoId, productId, title, rating, count){
		Brightcove.load(brightcoveId);
		Brightcove.reloadInfo(title, videoId, rating, count);
		var url = $j("#fox-ratings-form-baseurl").val() + "video/index/related/product_id/"+ productId;
		var productUrl = $j("#fox-ratings-form-baseurl").val() + "catalog/product/details/id/"+productId;
		$j.ajax({method:"GET",url: url,dataType: "json",success: printRelatedVideos});
		$j.ajax({method:"GET",url: productUrl,dataType: "json",success: printProductInfo});
	}
	Brightcove.reloadInfo = function(title, vid, rating, count){
		$j("#fox-ratings-form-bid").val(vid);
		$j("div.clip-info div.clip").html("<span>Clip: </span>"+ title);
		
		var ratingTxt = '<span class="rating-title">'+$j("#fox-video-rating span.rating-title").html()+'</span>';
		for (var i=1; i<=5; i++){
			ratingTxt += '<input name="star1" value="'+i+'" type="radio" class="foxstar"';
			if (rating == i) ratingTxt += 'checked="checked"'
			if ($j("#fox-ratings-authenticated").val() != "1") ratingTxt += ' disabled="disabled" ';
			ratingTxt += '/>';
		}
		ratingTxt += '<span class="views">'+rating+' of 5 ('+count+' review';
		if(count != 1) ratingTxt+='s';
		ratingTxt += ')</span>';
		$j("#fox-video-rating").html(ratingTxt);
		$j("#fox-video-rating").find('input.foxstar').rating({ callback: function(value, link){	submitRating(value, 'fox-ratings-form-bid', 'fox-ratings-form-baseurl', true);}});
	}
	Brightcove.printRatings = function(results){
		var rating = Math.floor(parseFloat(results.average));
		var isLoggedIn = false;
		if(results.loggedIn == 1)
		  isLoggedIn = true;
		$j('#fox-ratings-authenticated').val(results.loggedIn);
		var ret = "<span class='rating-title'>";
		if(!isLoggedIn) ret += "Log In to ";
		ret += "Rate this Video/Average Rating:</span>";
		for(var i=1; i<=5; i++){
			ret += "<input type='radio' class='starrating' name='videorating' value='"+i+"'";
			if(i == rating) ret+= " checked='checked' ";
			if(!isLoggedIn) ret+= " disabled='disabled' ";
			ret +=" />";
		}
		ret += "<span class='views'>"+rating+" of 5 (";
		ret += results.count + " review";
		if(results.count != 1) ret+= "s";
		ret += ")</span>";
		$j('#fox-video-rating').html(ret);
		$j('#fox-video-rating').find('input.starrating').rating({
			callback: function(value, link){
				submitRating(value, 'fox-ratings-form-bid', 'fox-ratings-form-baseurl', true);
			}
		});	
		$j('#fox-video-rating').show();
	}
	printProductInfo = function(result){
		$j("#video-format").html(result.product.format).attr("href", result.product.url);
		$j("#video-url").attr("href", result.product.url);
		$j("#video-price").text("$"+result.product.price);
		$j("#video-add-to-cart").attr("href", result.product.addToCart);
		// there are additional formats
		var add="";
		if (!tbCommon.isArray(result.product.formats)) for (var k in result.product.formats) { if (k != result.product.format) add += "<a href='" + result.product.formats[k].url + "'>" + k + " $" + result.product.formats[k].price + "</a>";}
		$j('td.additional').html(add);
	}
	printRelatedVideos = function(results){
		var html = '';
		if (!tbCommon.isArray(results)) {
			var key;
			for (key in results) {html += '<div>'+getResultHtml(results[key])+'</div>';}
			$j('div.vid-scrollable div.items').html(html);
			Brightcove.playlist = $j('#related-video a.brightcove');
			Brightcove.index = -1;
			$j('div.vid-scrollable div.items div').each(function(){
				$j(this).find('input.foxstar').rating();
				$j("div.video-rating").show();
			});
			$j('a.brightcove').click(Brightcove.click);
		} else {
			$j('div.vid-scrollable div.items').html(html);
		}
	}
	
	getResultHtml = function(result){
		var related = "";
		var thumb = result.thumbnail_path;
		if(!thumb)
			thumb = $j('#magento-skin-url').val()+'images/video-bg.png';
		related += '<img src="'+thumb+'" alt="'+result.title+'" /><div>';
		related += '<a href="#" class="brightcove" id="brightcove-'+result.brightcove_id+'">'+result.title+'</a>';
		related += '<div class="time-views">('+ getVideoDuration(parseInt(result.length)) +' minutes) - '+ result.views+' views</div><div class="video-rating">';
		related += '<input type="hidden" class="video-id" name="video-id" value="'+result.video_id+'" />';
		var rating;	if ( result.avg_rating == null ) rating = 0; else rating = Math.ceil(parseFloat(result.avg_rating));
		related += '<input type="hidden" class="video-rating" name="video-rating" value="'+rating+'" />';
		related += '<input type="hidden" class="video-count" name="video-count" value="'+result.rating_count+'" />';
		for (var i=1; i<=5; i++){
			related += '<input name="star1" value="'+i+'" type="radio" class="foxstar"';
			if (rating == i) related += 'checked="checked"';
			related += ' disabled="disabled" />';
		}
		related += '<span>'+rating+' of 5 ('+result.rating_count+' review';
		if ( parseInt(result.rating_count) != 1) related += 's';
		related += ')</span></div></div>';
		return related;
	}
	
	getVideoDuration = function(ms){var min=Math.floor(ms / 60000), sec=(Math.floor(ms / 1000)) % 60;return padDigits(min,2) + ":" + padDigits(sec, 2);}
	padDigits = function(n, totalDigits){n=n.toString(); var pd=''; if(totalDigits > n.length) for(i=0; i<(totalDigits-n.length); i++){pd += '0';} return pd+n.toString();} 
	
	$j('a.brightcove').live("click", Brightcove.click);
	if($j('#fox-video-rating').length > 0){
		var url =$j('#fox-ratings-form-baseurl').val() + "rating/clip/prep/id/" + $j("#fox-ratings-form-bid").val()+"/";
		$j.ajax({method:"get", dataType:"json", url:url, success:Brightcove.printRatings, error:function(){} });
	}
	/* Video Grid Filtering / Pagination / Search */
	$j('#filter-items-per-page, #filter-sort-by-field, #select-genre-filter').change( function() { 
		var baseurl = $j('#magento-base-url').val();  
		var category = $j('#magento-base-category').val();  
        var selectedGenre = $j('#select-genre-filter').val( );            
        var section = Brightcove.getActiveSection();    	
		var cPageSize = $j('#filter-items-per-page').val();
		var cFilter = $j('#filter-sort-by-field').val();    
		var order = '/order/'+cFilter;
		if (section=='rated') order = '';
		var action='lookup';
		if (section == "search") action = 'search';
		var url = baseurl+'video/index/'+action+'/section/' + section + '/category_id/'+category+'/filter/' + selectedGenre+'/page/1/ipp/'+cPageSize+order+'/';
        if (section == "search" ) url += 'q/'+$j('#vid-gridSearch').val();
		Brightcove.getGridItems( url, section, true );     
      }); 
	  
	 $j('#fox_tab_container table.pager td.pages ol li a').live("click", function(e){
	 	e.preventDefault();
		if ($j(this).hasClass('active') ) {return;}
		else {
			var baseurl = $j('#magento-base-url').val();   
			var category = $j('#magento-base-category').val();
			var page;
			if ($j(this).hasClass('prev')){
				var current = $j('table.pager td.pages ol li a.active').text();
				page = parseInt(current) - 1;
			} else if ($j(this).hasClass('next')) {
				var current = $j('table.pager td.pages ol li a.active').text();
				page = parseInt(current) + 1;
			} else {
				var page = $j(this).text();
			}
			var selectedGenre = $j('#select-genre-filter').val( );            
        	var section = Brightcove.getActiveSection();
			var cPageSize = $j('#filter-items-per-page').val();
			var cFilter = $j('#filter-sort-by-field').val();  
			var order = '/order/'+cFilter;
			if ( section == 'rated' ) order = '';
			var action = 'lookup';
			if (section == "search") action = 'search';
			var url = baseurl+'video/index/'+action+'/section/' + section + '/category_id/'+category+'/filter/' + selectedGenre+'/page/'+page+'/ipp/'+cPageSize+order+'/';
			if (section == "search" ) url += 'q/'+$j('#vid-gridSearch').val();
			Brightcove.getGridItems( url, section, true );   
		}
	 });
	 
	 Brightcove.videoTabsAction = function(e){
		e.preventDefault();
		var href = $j(this).attr('href');
		var hrefArray = href.split("#");
		href = hrefArray[hrefArray.length - 1];
		$j('#fox_tabs .active').removeClass('active');
		$j(this).parents('li').addClass('active');
		$j('.vid-grid-listing').hide();
		$j('#div-grid-view-'+href).show();
		
		// if page size, genre, sort are same just show, otherwise refetch
		var cPageSize = $j('#filter-items-per-page').val();
		var cGenre = $j('#select-genre-filter').val();
		var cFilter = $j('#filter-sort-by-field').val();
		var sPageSize = $j('#'+href+'-count').val();
		var sGenre = $j('#'+href+'-filter').val();
		var sFilter = $j('#'+href+'-order').val();
		var sPage = $j('#'+href+'-page').val();
		if (sPage == undefined){ sPage = 1; }
		if ( href == 'rated'){$j('td.sort-by').css({visibility:"hidden"});} else {$j('td.sort-by').css({visibility:"visible"});}
		if ( (sPageSize == sGenre == sFilter == undefined) || (cPageSize != sPageSize) || (cGenre != sGenre) || (cFilter != sFilter) ){
			var order = '/order/'+cFilter;
			if (href == 'rated') order=''; 
			var action = 'lookup';
			if (href=="search") action = 'search';
			var baseurl = $j('#magento-base-url').val();
			var category = $j('#magento-base-category').val();
			var url = baseurl+'video/index/'+action+'/section/' + href + '/category_id/'+category+'/page/'+sPage+'/ipp/'+cPageSize+order+'/filter/'+cGenre+'/';
			if (href == "search" )url += 'q/'+$j('#vid-gridSearch').val();
			Brightcove.getGridItems( url , href, true);
		} else {buildPagination(href);}
	}
	Brightcove.timeout;
	Brightcove.videoType = function(){
		clearTimeout(Brightcove.timeout);
		Brightcove.timeout = setTimeout(function(){
			str = $j('#vid-gridSearch').val();
			if (str.length >= 3){
				Brightcove.videoSearch(str);
			}
		}, 1000);
	}
	Brightcove.videoSearch = function(query) {
		var cQuery = '/q/'+query;
		var cPageSize = '/ipp/'+$j('#filter-items-per-page').val();
		var cGenre = '/filter/'+$j('#select-genre-filter').val();
		var cFilter = '/order/'+$j('#filter-sort-by-field').val();
		var cPage = '/page/1';
		var baseurl = $j('#magento-base-url').val();
		var url = baseurl+'video/index/search'+cQuery+cPageSize+cPage+cGenre+cFilter;
		if ( $j('#div-grid-view-search').length == 0) {
			// create a new tab, and make it active
			$j('#fox_tabs ul').append('<li><a id="search-results" href="#search">Results</a></li>');
			$j('div.panes').append('<div id="div-grid-view-search" class="vid-grid-listing padder"></div>');
			$j("#fox_tabs ul li a").click( Brightcove.videoTabsAction );
			$j('#search-results').trigger("click");
		} else {
			$j('#search-results').trigger("click");
			Brightcove.getGridItems(url, 'search', true);
		}
		$j('#vid-gridSearch').unbind("keyup",Brightcove.videoType).bind("keyup", Brightcove.videoType);
	}
    Brightcove.getGridItems = function( url, elementId, ajax ) {   
		showLoadingAnimation();     	      	  
    	$j.ajax({ type: "GET", url: url, success: writeGrid, error: function(resp) {}});
    } 
	$j('#vid-gridSearch').keyup(Brightcove.videoType);
	function buildPagination(section){
		var sPageSize = $j('#'+section+'-count').val();
		var total = $j('#'+section+'-total').val();
		var sPage = $j('#'+section+'-page').val();
		var pages = Math.ceil(parseFloat(total) / parseFloat(sPageSize));
		var start = 1;
		var limit = pages > 5 ? 5 : pages;
		if ( sPage > 5){
			var range = Math.floor((sPage-1) / 5);
			start = range * 5 + 1;
			var end = start + 4;
			limit = pages > end ? end : pages;
			if (limit == pages) start = pages - 4;
		}
		var html = "";
		if (sPage > 1){
			var img = $j('#magento-skin-url').val() + '/images/pager_arrow_left.gif';
			html += "<li><a href='#' class='prev'><img src='"+img+"' /></a></li>";
		}
		for (var i=start; i<=limit; i++){
			html += "<li><a href='#'";
			if(parseInt(sPage) == i) html+= " class='active' "
			html+=">"+i+"</a></li>";
		}
		if (sPage < pages){
			var img = $j('#magento-skin-url').val() + '/images/pager_arrow_right.gif';
			html += "<li><a href='#' class='next'><img src='"+img+"' /></a></li>";
		}
		$j('#fox_tab_container table.pager td.pages ol').html(html);
	}

	Brightcove.getActiveSection = function(){
		// Get active section and populate it for the genre selected
		//return 'all';
		var active = $j("#fox_tabs .active");
		var section = "all";
		if (active.length > 0) {
			section = $j(active).find('a');
			if(section.length > 0) section = section.attr("href");
			else section = $j(active).attr("href");
			var sectionArray = section.split("#");
			section = sectionArray[sectionArray.length - 1];
			return section;
		}
	}

	Brightcove.playClip = function( event ) {
    	// Update video player to play new clip.
    	var brightcove_id = $j(this).attr('id').substring(4);
    	var pid = $j(this).attr('pid');
		var vid = $j(this).attr('vid');
		var parents = $j(this).parents('.vid-grid-desc-bg');
		var title = parents.find('h5 a').text();
		var rating = parents.find('input.video-rating').val();
		var count = parents.find('input.video-count').val();
		Brightcove.queue( brightcove_id, vid, pid, title, rating, count);
	}
	function writeGrid( response ) {
		var section = Brightcove.getActiveSection();
	    var elementId = "div-grid-view-"+section;    
	    $j("#"+elementId).empty().html(response);
	    buildPagination(section);
		resetRatings(section);
	    hideLoadingAnimation();
	}
	function resetRatings(section){
		$j("#div-grid-view-"+section).find('.ratings-block').each(function(){
			$j(this).find('input.foxstar').rating();
			$j(this).show();
		});
	}
	function showLoadingAnimation(){  
		var height = $j('div.panes').height();
		if ( height < 80) height = 80;
		if ($j("div.promo-overlay").length > 0) {$j("div.promo-overlay").css({height: height+"px"}).show();
		} else {
			var url = $j('#magento-skin-url').val() + 'images/loading.gif';
			$j("div.panes").prepend("<div class='promo-overlay'><img src='"+url+"' /></div>");
			var width = $j('div.panes').width();
			$j("div.promo-overlay").css({opacity:0.5, height: height+"px", width:width+"px"});
			$j("div.promo-overlay img").css({paddingTop: "20px" });
			$j("div.promo-overlay").show();
		}
	}
	function hideLoadingAnimation(){ $j("div.promo-overlay").hide();} 
	
	/* tbBigDog */
	tbBigDog.gallery = ""
	tbBigDog.createGallery = function(){
		var bg_img = $j('#gallery-initial-on').val();
		$j('#feature').galleryView({
      		panel_width: 1000,
      		panel_height: 325,
      		frame_width: 176,
      		frame_height: 89,
      		border: 'none',
      		slide_method: 'pointer',
	  		pointer_index: 2,    
	  		background_img: bg_img,
      		pause_on_hover: true
    	});
	    $j(document).stopTime("transition");
		$j("#feature").galleryView.pause();
		tbBigDog.lookup();
	}
	tbBigDog.lookup = function(){
		var url = $j('#gallery-base-url').val() + 'featuredtitles/index/lookup/id/';
		var id = $j('#gallery-category').val();
		url += id + '/';
		$j.ajax({ method: "get", url: url, success: tbBigDog.results, error: function(){} });
	}
	tbBigDog.results = function(results){
		var oldPanels = $j('#feature').find('div.panel');
		$j('#feature').append('<div id="temp" style="display:none;"></div>');	// temporary container for results
		$j('#temp').html(results);											// write results to container
		var newPanels = $j('#temp').find('div.panel');
		
		for(i=0; i<newPanels.length; i++){
			oldPanels.eq(i).html(newPanels.eq(i).html());
		}
		$j('#temp').remove();
		$j('#feature img.nav-next').trigger('click');
		$j("#feature").galleryView.restart();
		$j('.ymal-image').hoverIntent(function(){$j(this).find('.quickview').fadeIn();},function(){setTimeout(function(){},500); $j(this).find('.quickview').fadeOut('fast');});
	}
	ymal.updateAlsoLike = function(response, elementId) {
		$j(elementId).replaceWith(response);
	}
	getAlsoLikePage = function(url, elementId) { ymal.getAlsoLikePage(url, elementId); }
	ymal.getAlsoLikePage = function(url, elementId){
		ymal.showProgressAnimation();
		$j.ajax({
			type: "GET",
			dataType:"html",
			url: url,
			success: function(resp){ ymal.hideProgressAnimation(); ymal.updateAlsoLike(resp, elementId); },
			error: function(resp){}
		});
	}
	ymal.currentProgress = "";
	ymal.showProgressAnimation = function(){
    	var container = $j('.ymal-container:visible');
		var img = $j('div.ajax-overlay img').attr('src');
		container.append('<div class="loading-overlay" style="display:none;"><img src="'+img+'" /></div>');
		ymal.currentProgress = container.find('div.loading-overlay');
		var height = ymal.currentProgress.parents('div.other-container').height();
		var width = ymal.currentProgress.parents('div.other-container').width();
		var diff = height - ymal.currentProgress.find('img').height() - 40;
		ymal.currentProgress.css({opacity:0.5, height: height+"px", width:width+"px"});
		ymal.currentProgress.find('img').css({paddingTop: (diff / 2)+"px" });
		ymal.currentProgress.show();
	}
	ymal.hideProgressAnimation = function(){
		ymal.currentProgress.hide();
	}
	if ($j("#feature").length > 0) tbBigDog.createGallery();
	
	tbGrid.getActiveSection = function(){
		return $j('#fox_tabs').find('li.active a').text();
	}
	tbGrid.getMode = function(){
		var mode = $j('td.mode a.on').attr('id');
		return mode.split('mode-')[1];
	}
	tbGrid.results = function(results){
		$j('div.listing-type-grid').html(results);
	}
	tbGrid.update = function(){
		var category = '/category_id/'+$j('#category_id').value();
		var section = '/section/'+tbGrid.getActiveSection();
		var genre = '/genre/'+$j('#select-genre-filter').value();
		var price = '/price/'+$j('#select-price-filter').value();
		var format = '/format/'+$j('#select-format-filter').value();
		var sort = '/sort/'+$j('td.sort-by select').value();
		var order = '/order/'+$j('td.order-by select').value();
		var page = '/page/' + $j('.pages ol li .on').text();
		var limit = '/limit/' + $j('td.pagesize select').value();
		var mode = '/mode/'+ tbGrid.getMode();
		var url = $j('#grid-base-url').value()+'/catalog/product/lookup' + category + section + genre + price + format + sort + order + page + limit + mode + '/';
		$j.ajax({method:"get", url:url, success:tbGrid.results});
	}
});

/* from ajaxcart.js */
function ajaxcartsend(url, type, obj){
 	if (type == 'form'){ 
 		var action = $j('#product_addtocart_form').attr("action");
		action+=url; 
		var str = $j('#product_addtocart_form').serialize();
 		$j.ajax({type: "POST",data: str, dataType:"json", url: action,success: function(resp){updateCartView(resp);},error: function(resp){ window.location.href = url; }});
 	}
 	if (type == 'url') $j.ajax({type: "GET", dataType:"json",url: url, success: function(resp){updateCartView(resp);}, error: function(resp){window.location.href = url;}});
}

function setLocationFC(url, node){
	window.scrollTo(0, 0);
	showProgressAnimation();

  // track the add to cart action
  try {
    pageTracker._trackPageview (url);
    rollupTracker._trackPage (url);
  } catch (error) { }
    
	if (url.substring(url.length - 1) != "/") { url += "/";} 
	if(FC_TBJS.isCartPage && ((url.search('/add') != -1 ) || (url.search('/remove') != -1 )) ){window.location.href=url+"is_checkout/1";
 	}else if (url.search('checkout/cart/add') != -1 ){ ajaxcartsend(url+'tbjs/1', 'url', '', ''); tbAddToCart.currentLink = $j(node);
 	}else if (url.search('checkout/cart/delete') != -1){ ajaxcartsend(url+'tbjs/1', 'url', '', '');
	}else {	window.location.href = url;	} 
	return false;
}

function showProgressAnimation(){
	var height = $j('div#main').height();
	var windowHeight = $j(window).height();
	var width = $j('div#main').width();
	var diff = windowHeight - $j('div.ajax-overlay img').height();
	$j("div.ajax-overlay").css({opacity:0.5, height: height+"px", width:width+"px"});
	$j("div.ajax-overlay img").css({paddingTop: (diff / 2)+"px" });
	$j("div.ajax-overlay").css({opacity:0.5, height: height+"px",top:0});
	if ($j('div#main > div.ajax-overlay').length == 0) $j("div#main").append($j('div.ajax-overlay'));
	$j('div.ajax-overlay').show();
	$j('a.top-link-cart').mouseover(function(){$j(this).css({backgroundPosition:"-683px -72px", cursor:"default"});})
	$j('a.top-link-cart').bind('click', disableCart);
}
function hideProgressAnimation(){
	$j("div.ajax-overlay").hide();
	$j('a.top-link-cart').mouseover(function(){$j(this).css({backgroundPosition:"-683px -96px", cursor:"pointer"});});
	$j('a.top-link-cart').mouseout(function(){$j(this).css({backgroundPosition:"-683px -72px", cursor:"pointer"});});
	$j('a.top-link-cart').unbind('click', disableCart);
}
function disableCart(e){e.preventDefault();}
function updateCartView(response){
	hideProgressAnimation();
	if ( response.method == "delete") { decreaseCounter(response.counter);hideCart();} else {
    // log the spotlight trigger
    var axel = Math.random()+"";    var a = axel * 10000000000000;
    var dblClickUrl = 'http://fls.doubleclick.net/activityj;src=1393346;type=foxst552;cat=foxst530;u2=' + response.product.title + ';u4=1;ord='+ a;
    $j.ajax ({ method: 'get', dataType: 'script', url: dblClickUrl});

		var price = response.product.price;
		var url = response.product.removeUrl;
		var row = "<td>" + response.product.title + "</td><td>$"+price + "</td><td><a href='#' class='remove' onclick='setLocationFC(\""+url+"\", this)' title='Remove'>Remove</a></td>";
		if ( $j('#ajax-cart').length > 0 ) { $j('#ajax-cart tbody tr').html(row);} else {$j('a.top-link-cart').parent().append("<div id='ajax-cart' style='display:none'><table cellspacing='0' cellpadding='0' border='0'><thead><tr><th class='c1'>Product</th><th class='c2'>Price</th><th class='c3'>&nbsp;</th></tr></thead><tbody><tr>"+row+"</tr></tbody></table></div>"); $j('#ajax-cart').hover(function(){ clearTimeout(FC_TBJS.timeout); }, function(){ FC_TBJS.timeout = setTimeout(hideCart, FC_TBJS.TIMEOUT_VAL); });}
		increaseCounter();
		showCart();
		tbAddToCart.currentLink.attr('href', response.product.addUrl);
	}
}
function increaseCounter(){var txt = $j("a.top-link-cart").text();if (txt != "") {var val = txt.split("(")[1];txt = val.split(")")[0];val = parseInt(txt) + 1; $j("a.top-link-cart").text("(" + val + ")");}}
function decreaseCounter(val){ var txt = $j("a.top-link-cart").text(); if (txt != "") $j("a.top-link-cart").text("(" + val + ")");}
function showCart(){$j('#ajax-cart').slideDown('slow'); FC_TBJS.timeout=setTimeout(hideCart, FC_TBJS.TIMEOUT_VAL);}
function hideCart(){$j('#ajax-cart').slideUp('slow');}
function coverflowAddToCart(url){setLocationFC(url, window);}
function modalAddToCart(url, node){$j("#modal .close").trigger("click");setLocationFC(url, node);}
