/*!
 * HTML5 Placeholder jQuery Plugin v1.8.3
 * @link http://mths.be/placeholder
 * @author Mathias Bynens <http://mathiasbynens.be/>
 */
(function(f){var e='placeholder' in document.createElement('input'),a='placeholder' in document.createElement('textarea');if(e&&a){f.fn.placeholder=function(){return this};f.fn.placeholder.input=f.fn.placeholder.textarea=true}else{f.fn.placeholder=function(){return this.filter((e?'textarea':':input')+'[placeholder]').bind('focus.placeholder',b).bind('blur.placeholder',d).trigger('blur.placeholder').end()};f.fn.placeholder.input=e;f.fn.placeholder.textarea=a;f(function(){f('form').bind('submit.placeholder',function(){var g=f('.placeholder',this).each(b);setTimeout(function(){g.each(d)},10)})});f(window).bind('unload.placeholder',function(){f('.placeholder').val('')})}function c(h){var g={},i=/^jQuery\d+$/;f.each(h.attributes,function(k,j){if(j.specified&&!i.test(j.name)){g[j.name]=j.value}});return g}function b(){var g=f(this);if(g.val()===g.attr('placeholder')&&g.hasClass('placeholder')){if(g.data('placeholder-password')){g.hide().next().attr('id',g.removeAttr('id').data('placeholder-id')).show().focus()}else{g.val('').removeClass('placeholder')}}}function d(h){var l,k=f(this),g=k,j=this.id;if(k.val()===''){if(k.is(':password')){if(!k.data('placeholder-textinput')){try{l=k.clone().attr({type:'text'})}catch(i){l=f('<input>').attr(f.extend(c(this),{type:'text'}))}l.removeAttr('name').data('placeholder-password',true).data('placeholder-id',j).bind('focus.placeholder',b);k.data('placeholder-textinput',l).data('placeholder-id',j).before(l)}k=k.removeAttr('id').hide().prev().attr('id',j).show()}k.addClass('placeholder').val(k.attr('placeholder'))}else{k.removeClass('placeholder')}}}(jQuery));

$.ajaxSetup({
    cache: false
});

var FHBtimeout = "";
var FixZIndexBugs = false;
var addthis_config = {};

var Snag = { 
	
/*	------------------------------------------------------------------------------------------
	ADD THIS

	Implement add this
	------------------------------------------------------------------------------------------ */	
	addThis: {
		init: function() {
			//late load the add this JS dependency to avoid hanging collisions with other JS
	        addthis_config = {
	            data_track_clickback: true,
	            services_compact: 'facebook,twitter,aim,favorites,delicious,digg,google,myspace,live,stumbleupon,more',
	            services_custom: {
	                name: "Clicker",
	                url: "http://www.clicker.com/checkin/?url={{url}}&checkin=true&pageTitle={{title}}&pageUrl={{url}}",
                    icon: "http://www.clicker.com/images/general/favicon.ico"
	            }
				//ui_delay: 500,
				//ui_use_css: false
	        };
	        jQuery.getScript("http://s7.addthis.com/js/250/addthis_widget.js#username=snagfilms&domready=1");
		}
	},  
	
/*	------------------------------------------------------------------------------------------
	AJAX LOAD

	This is the load used to re-load large sections of the page
	------------------------------------------------------------------------------------------ */
	ajaxLoad: {
		container: "",
		load: function(url, cb, container) {
			var obj = container ? container : this.container;
			$(obj).load(url + ' ' + obj + ' > *', cb);
		},
		setContainer: function(s) {
			this.container = s;
		}
	},

/*	------------------------------------------------------------------------------------------
	BROWSE

	Controls Scrolling and interaction of the lead carousel
	------------------------------------------------------------------------------------------ */		
	browse: {
		FHB: {},
		cookieName: "snag-browse",
		lastHash: "",
		init: function() {
		    $(window).bind('hashchange', function() {
                if (parseInt(location.hash.replace("#","")) < Snag.browse.lastHash) {
          		    Snag.browse.refreshResults(Snag.Utils.cookie.get(Snag.browse.cookieName));
          		}
            });
            
			Snag.ajaxLoad.setContainer(".current-results");		// Set ajax load container
			$('.nav .categories .selected').append('<span class="marker"></span>');

			$('.browse form button').hide();			// Button only needs to show if JS is not enabled
			Snag.browse.initSlider();
			$('#frm-filter select, #frm-filter .run-time input, #filter-worldwide').change( function(event) {Snag.browse.doFilterSubmit(event);});
			if (FixZIndexBugs) {
				// Fix browse drop down menus to be on top of the ones beneath
				$('#frm-filter > div').each(function(index) {$(this).css('z-index', 50-index);});
			}

			this.reInit();
		},
		reInit: function() {
			$('.current-results').append('<div class="loading"></div>');
			$('.your-filters li').each( function() {	// Replace the text for 5 stars in the filter
				o = $(this);
				o.html(Snag.Utils.UI.makeStars(o.html()));
			});
			Snag.browse.initFHB();
			// Enabale Pagination
			Snag.Utils.Pagi('.current-results', function() {Snag.browse.reInit();});		
			$('.view a').click( function(e) {e.preventDefault();Snag.browse.refreshResults(this);$('#frm-filter')[0].view.value = this.getAttribute('data-type');});
			$('#slt-sort').change( function() { 
					var oSlt = $('#slt-sort')[0]; 
					var oFrm = $('#frm-filter')[0];
					oFrm.sort.value = oSlt.options[oSlt.selectedIndex].getAttribute('data-value'); 
					oFrm.ltr.value = ''; 
					Snag.browse.refreshResults(oSlt.value); 
			});
			$('.your-filters a').click( function(e) {e.preventDefault();Snag.browse.resetFilter(this);Snag.browse.refreshResults(this);});
			$('.a-z a').click( function(e) { 
					e.preventDefault(); 
					var l = $(this).html(); 
					$('#frm-filter')[0].ltr.value = (l.toUpperCase() != 'ALL') ? l : '';
					Snag.browse.refreshResults(this); 
			});
					
			Snag.Utils.UI.select.init('.current-results');   
			$('.sort-view .sort').show();
			Snag.fb.reInit();
			if (FixZIndexBugs) {
				$('.grid-view .films-list li').css({'z-index': 40, 'position' : 'relative'});
			}
		},
		initFHB: function() {
			if ($('.grid-view').length > 0) {
				this.FHB = new Snag.Utils.FilmHoverBox.Box(5);
				$('.grid-view .films-list li').hover( 
					function() {if (FixZIndexBugs) {$(this).css('z-index', '100');}Snag.browse.FHB.show(this);}, 
					function() {Snag.browse.FHB.hide(this);if (FixZIndexBugs) {$(this).css('z-index', '40');}} 
				);
			}
		},
		initSlider: function() {
			try {
				var RT = $('.run-time');
				var Min = RT.find('[name="min-time"]')[0];
				var Max = RT.find('[name="max-time"]')[0];
				RT.append('<div id="run-time-range"></div>');
				$("#run-time-range").slider({
					range: true,
					min: Min.getAttribute('data-value'),
					max: Max.getAttribute('data-value'),
					values: [Min.getAttribute('data-value'), Max.getAttribute('data-value')],
					slide: function( event, ui) {
						Min.value = ui.values[0];
						Max.value = ui.values[1];						
					},
					change: function(event) {Snag.browse.doFilterSubmit(event);}
				});
			} catch(e) {
				// Do Nothing, it's not on the page
			}
		}, 
		doFilterSubmit: function(event) {
			$('.current-results .loading').show();
			Snag.browse.refreshResults(location.pathname + "?" + $('#frm-filter').serialize());
                        switch (event.target.id) {//GA tracking
                            case 'run-time-range':
                                var trackLabel = 'filter-runtime';
                                break;
                            default:
                                var trackLabel = event.target.id;
                        }
                        Snag.Tracking.GA.trackEvent("browse", trackLabel);
		},
		refreshResults: function(url) {
			var oLoad = $('.current-results .loading');
			this.lastHash = location.hash = +new Date();
			sURL = (url.href) ? url.href : url;
			Snag.Utils.cookie.set(Snag.browse.cookieName, sURL);
			oLoad.show();																							
			Snag.ajaxLoad.load(url, function() {oLoad.hide();Snag.browse.reInit();Snag.Utils.ScrollTop();});
		},
		resetFilter: function(o) {
			switch (o.getAttribute('data-type')) {
				case 'tag':
					Snag.Utils.UI.select.resetToDefault('#filter-tag');
					break;
				case 'run-time':
					var RT = $('.run-time');
					var  min = RT.find('[name="min-time"]')[0];
					var max = RT.find('[name="max-time"]')[0];
					min.value="";
					max.value="";
					$("#run-time-range").slider({
						values: [min.getAttribute('data-value'), max.getAttribute('data-value')]
					});
					break;
				case 'stars':
					Snag.Utils.UI.select.resetToDefault('#filter-rating');
					break;
				case 'channel':
					Snag.Utils.UI.select.resetToDefault('#filter-channel');
					break;
                                case 'type':
					Snag.Utils.UI.select.resetToDefault('#filter-type');
					break;
				case 'worldwide':
					$('#filter-worldwide')[0].checked = false;
					break;
				default: 

			}

		}
	},

/*	------------------------------------------------------------------------------------------
	Connect

	"Connect" module; needs click tracking
	------------------------------------------------------------------------------------------ */
        connect: {
            init: function() {
                $('.connect a').click(function(event){
                   Snag.Tracking.GA.trackEvent("connect module", event.currentTarget.className);
                });
            }
        },


/*	------------------------------------------------------------------------------------------
	DYNAMIC LEAD

	Controls Scrolling and interaction of the lead carousel
	------------------------------------------------------------------------------------------ */
	leadCarousel: {
		transSpeed: 500, 	// speed of transition between slides
		autoSpeed: 8000,	// delay between auto-roation of slides
		interval:0,
        rolloverTracked: false,
		init: function() {
			if ($('.lead-panes').length > 0) {
				// Begin loading of other DL images other than the first
				$('.lead-content > a:first-child').each(function(index) {
				    var o = $(this);
				    if (o.has('img').length < 1) {
				        o.append('<img src="' + o[0].getAttribute('data-image') + '" alt="" />');
				    }
				});
				$(".lead-panes").scrollable({ 
									circular: true, 
									keyboard: true, 
									speed: this.transSpeed,
									// hide dots before slide and add them back in after, shifted left or right depending on the format of the slide
									onBeforeSeek: function(event, tabIndex) {
										$('.lead .slide-dots').hide();
									},
									onSeek: function(event, tabIndex) {
										var i = this.getItems()[tabIndex];
										var sd = $('.lead .slide-dots');
										$(i).hasClass("right") ? sd.addClass('right') : sd.removeClass('right');
										sd.show();
									}
								}).navigator({
									navi: '.slide-dots',
									naviItem: 'a',
									activeClass: 'selected'
								}).autoscroll(this.autoSpeed);

                //Home page GA tracking
                $('.home-page .lead-content').mouseenter(function() {
                    if (!Snag.leadCarousel.rolloverTracked) {
                        Snag.Tracking.GA.trackEvent("home", "dl-ro");
                        Snag.leadCarousel.rolloverTracked = true;
                    }
                });
                $('.home-page .lead-content a').click( function(event) {
                    var dlNum = $(".lead-panes").data("scrollable").getIndex() + 1;
                    Snag.Tracking.GA.trackClick(event, "home", "dl-" + dlNum);
                });
                $('.home-page .lead .slide-dots a, .home-page .lead .nav span').click( function(event) {
                    Snag.Tracking.GA.trackEvent("home", "dl-navclick");
                });

			}
		}
	},

/*	------------------------------------------------------------------------------------------
	FACEBOOK

	Everything related to interacting with Facebook in the JS
	------------------------------------------------------------------------------------------ */
	fb: {
		init: function() {
			$('.btn-fb').click( function(event) {Snag.fb.login(event);});
		},
		login: function(e) {
			e.preventDefault();
            Snag.Tracking.GA.trackEvent('registration and profiles', 'login');
			FB.login('', {scope: 'email'});
		},
		reInit: function(s) {
			try {
				var o = (s) ? $(s).get(0) : $('.current-results').get(0);
				FB.XFBML.parse(o);
			} catch(e) {
				// Do nothing, mostly likely there were no FB tags on the page
			}
		}
	},

/*	------------------------------------------------------------------------------------------
	FEATURED FILM MODULES

	These are the image/blurb film promos that show up on various pages -- all cats, all channels,
            home page, filmanthropy cause page carousel, etc.
	------------------------------------------------------------------------------------------ */
	featCat: {
	    init: function() {
	        $(".wrap .featImg").hover(function(){
	            var p =  $(this).next().find("p");
	            p.slideDown(200);
	            $(this).parent().hover(null, function(){
	                p.slideUp(200);
	            });
	        }, null);
	    }
	},

/*	------------------------------------------------------------------------------------------
	FILM CONSUMPTION PAGE

	This is where everything for the film consumption page will go
	------------------------------------------------------------------------------------------ */
	film: {
		FHB: {},
        init: function() {
			// check that we're on the film consumption page
			if ($('.video-lead').length > 0) {
				this.rating.init();
				this.queue.init();

                                var relatedFilms = $('.related-films .films');

				// enable the film hover boxes
				if (relatedFilms.length > 0 ) {
					this.FHB = new Snag.Utils.FilmHoverBox.Box(3);
					$('.related-films li').hover( 
						function() {if (FixZIndexBugs) {$(this).css('z-index', '100');}Snag.film.FHB.show(this);}, 
						function() {Snag.film.FHB.hide(this);if (FixZIndexBugs) {$(this).css('z-index', '40');}} 
					);
				}	

				// Set the film credits to single column if less than four in a list
				$('.film-credits ol').each(function(i) {if (this.getElementsByTagName('li').length < 4) {$(this).addClass('lt4');}});
				$('.film-credits .credits').hide();

	            // Toggle the film credits open/closed
	            $('.movie-info .more').click(
	                function(event) {
	                    event.preventDefault();
						if ($(this).hasClass('open-arrow')) {
							Snag.film.fc.hide("slow");
						} else {
							Snag.film.fc.show("slow");
						}
	                }
	            );
				this.archivedComments.init();

				if (FixZIndexBugs) {
					$('.video-stats li').each(function(index) {
						$(this).css('z-index', 30-index);
					});
				}

	            // Panel (sidebar) bindings
	            $('#panel-share-close').click(function(event) {
	                event.preventDefault();
	                return SnagPlayer.share.close(event);
	            });
                    $('#panel-add-close').click(function(event) {
	                event.preventDefault();
	                return SnagPlayer.panel.close('add');
	            });
	            $('#panel-info-close').click(function(event) {
	                event.preventDefault();
	                SnagPlayer.panel.close('info');
	            });
	            $('#panel-info-credits').click(function() {
					Snag.film.fc.show(); 
				});
	            $('#panel-embed-close').click(function(event) {
	                event.preventDefault();
	                SnagPlayer.panel.close('embed');
	            });
	            $('#panel-anthropy-close').click(function(event) {
	                event.preventDefault();
	                SnagPlayer.panel.close('anthropy');
	            });
				SnagPlayer.embed.init();
                // Related Films tracking
                relatedFilms.find('li a').click(function(event) {
                    Snag.Tracking.GA.trackClick(event, "player", "related");
                });
                // Below-player tags/category/etc links tracking
                $('.staff-picks h3 a, .staff-picks li a').click(function(event) {
                    Snag.Tracking.GA.trackClick(event, "player", "tag-click");
                });
                // "Buy" link tracking
                $('a.buy').click(function(event) {
                    Snag.Tracking.GA.trackEvent("player", "buy");
                });
                // Filmanthropy Module click tracking
                $('.filmanthropy a').click(function(event) {
                    Snag.Tracking.GA.trackClick(event, "film page", "support-module");
                });
                
                // Other embed buttons to open embed panel
                $('.button_embed').click( function() { SnagPlayer.panel.doClick('embed')} );
            }
        },
	/*	------------------------------------------------------------------------------------------
		FILM CREDITS - Show and hide the film credits based on user actions
		------------------------------------------------------------------------------------------ */
		fc: {	// film-credits
			show: function(sSpeed) {
				if (sSpeed) {
					$('.credits').slideDown(sSpeed);	
				} else {
					$('.credits').show();
				}
				$('.movie-info .more').addClass('open-arrow');
			},
			hide: function(sSpeed) {
				$('.credits').slideUp(sSpeed);
				$('.movie-info .more').removeClass('open-arrow');
			}
		},
	/*	------------------------------------------------------------------------------------------
		FILM RATING - User actions to rate the film
		------------------------------------------------------------------------------------------ */
		rating: {
			init: function() {
				var oLi = $('.frm-star-rating li');
				$('.frm-star-rating ol').hover( function() {Snag.film.rating.hover.rated.goin();}, function() {Snag.film.rating.hover.rated.out();});
				oLi.hover( function() {Snag.film.rating.hover.goin(this)}, function() {Snag.film.rating.hover.out()});
				oLi.click( function() {var o = $(this).find('input')[0];
										o.checked = true; 
										Snag.film.rating.submit(o.value);} );
			},
			submit: function(rating) {
                                Snag.Tracking.GA.trackEvent("player", "rating-click");
				if (SNAG.loggedIn) {
					// AJAX call for submitting user rating
                    var filmId = $('#film-id').val();
                    if (filmId.length > 0) {
                        $.getJSON('/ajax/rating.jsp?id=' + filmId + '&r=' + rating, function(data){
                            $('#rating-count').html(data.count);
                            $('#prev-rating').val(rating);
							Snag.film.rating.changeAvg(data.average);
                        });
                    }
					Snag.film.rating.displayRated(rating);
				} else {
					$('#sng-login').remove();
					Snag.film.rating.showPopUp('<div id="sng-login" class="rating-pop">' + $('#login-to-rate').html() + '</div>');
					setTimeout("$('#sng-login').fadeOut(2000, function() { $(this).remove(); })" , 7000);
					$('#sng-login .btn-fb').click( function(event) {Snag.fb.login(event);$('#sng-login').remove();});
				}
			},
			changeAvg: function(rating) {
				$('span.stars').removeClass('s1 s2 s3 s4 s5').addClass('s'+rating);
			},
			displayRated: function(rating) {
				$('#sng-rp').remove();
				Snag.film.rating.showPopUp('<div id="sng-rp" class="rating-pop">Thank you for rating. <span class="stars r' + rating + '"></span></div>');
				setTimeout("$('#sng-rp').fadeOut(2000, function() { $(this).remove(); })" , 4000);
			},
			hover: {
				goin: function(o) {
					$('li > .stars').addClass('r' + ($(o).index() + 1));
				},
				out: function() {
					$('li > .stars').removeClass('r1 r2 r3 r4 r5');
				},
				// this shows the hover box if the user has already rated the film
				rated: {
					goin: function() {
						var pr = $('#prev-rating');
						if (pr.length > 0 && pr[0].value != "") {
							Snag.film.rating.showPopUp('<div id="sng-prp" class="rating-pop">Your current rating: <span class="stars r' + pr[0].value + '"></span></div>');
						}
					},
					out: function() {
						$('#sng-prp').remove();
					}
				}
			},
			showPopUp: function(sHTML) {
				$('.frm-star-rating').append(sHTML);
			}
		},
	/*	------------------------------------------------------------------------------------------
		OLD COMMENTS - Add showing and hiding of archived comments
		------------------------------------------------------------------------------------------ */
                archivedComments: {
                    init: function() {
                        $('.comment-archives').show();
                        $('.comment-archives .more-btn').click( function(e) {
                            e.preventDefault();
                            var ca = $('.comment-archive');
                            if (ca.is(":visible")) {
                                ca.hide();
                            } else {
                                ca.show();
                                Snag.Tracking.GA.trackEvent("film page", "older-comments");
                            }
                        });
                        $('.comment-archive .btn-close').click( function(e) {
                            e.preventDefault();
                            $('.comment-archive').hide();
                        });
                    }
                },
	/*	------------------------------------------------------------------------------------------
		QUEUE - Add to queue interactions specific to the film page
		------------------------------------------------------------------------------------------ */		
		queue: {
		    init: function() {
				$('.video-lead a.queue').click( function(e) {
				    e.preventDefault();
				    Snag.film.queue.add($(this).attr("data-action"));
				    Snag.Tracking.GA.trackEvent("player", "add-q");
				});
                $('#panel-add .btn-fb').click( function(event) {
                    Snag.fb.login(event);
                    vid.player.pause();//pauses video
                });
			},
			add: function(action) {
				if (!SNAG.loggedIn) {
					$('#sng-login').remove();
					$('#li-queue').append('<div id="sng-login" class="rating-pop">' + $('#login-to-add-to-queue').html() + '</div>');
					setTimeout("$('#sng-login').fadeOut(2000, function() { $(this).remove(); })" , 7000);
					$('#sng-login .btn-fb').click( function(event) {
                                            Snag.fb.login(event);
                                            vid.player.pause();//pauses video
                                            $('#sng-login').remove();
                                        });
				}
			}
		}
    },

/*	------------------------------------------------------------------------------------------
	FILMANTHROPY

	Stuff dealing with the filmanthropy pages. 
	------------------------------------------------------------------------------------------ */
	filmanthropy: {
		FHB: {},
		transSpeed: 250, 	// speed of transition between slides
		init: function() {
			// enable the film hover boxes
			if ($('.cause .related-films').length > 0 ) {
				this.FHB = new Snag.Utils.FilmHoverBox.Box(2);
				$('.related-films li').hover( 
					function() {Snag.filmanthropy.FHB.show(this);}, 
					function() {Snag.filmanthropy.FHB.hide(this);} 
				);
				// Bad hack for IE z-index issues
				if (FixZIndexBugs) {
    				var sbf = $('.sb-filter');
    				sbf.css('z-index', '1');
        			sbf.hover(
        			        function() { $(this).css('z-index', '100'); },
        			        function() { $(this).css('z-index', '1'); }
        			);
                }
			}
			if (FixZIndexBugs) {
				$('.cause').each( function(index) {$(this).css('z-index', 20+index)});
			}
			// Hook up the Find a Cause Drop Down
			var frmCause = $('.frm-slt-cause');
			if (frmCause.length > 0) {
				frmCause.find('input').hide();
				frmCause.find('select').change( function() {
				    var url = $(this).find('option').filter('option:selected').val();
				    if (url.length > 0) {
				        frmCause.attr('action', url);
				        frmCause.submit();
				    }
				});
            }
			// Small Carousel on Causes Page
			if ($('.smallCarousel').length > 0) {
				$('.next-a, .prev-a').click( function(event) {event.preventDefault();});
				$('.smallCarousel').scrollable({
										circular: false,
										keyboard: false,
										speed: this.transSpeed,
										next: ".next-a",
										prev: ".prev-a",
										onSeek: function(event, tabIndex) {
											$('.smallCarousel .count i').html(tabIndex + 1);
										}
				});									
			}
			// disable click for disabled buttons 
			$('.disabled a').click( function(e) {e.preventDefault();});
		}
	},

/*	------------------------------------------------------------------------------------------
	HAPPENING NOW
	
	Happening now with just viewed tab visible. Other tabs will be loaded on click with AJAX
	calls.
	------------------------------------------------------------------------------------------ */
	now: {		
		init: function() {
			$('.happening-now .tabs').tabs("div.panes > div", {
			            tabs: 'li',
			            current: 'selected',
			            onClick: function(event, tabIndex) {
			                		var paneData = jQuery.parseJSON($(event.currentTarget.getTabs()[tabIndex]).find("a").attr("data-pane"));
			                		if (paneData != null) {
										$('.happening-now .panes').append('<div class="loading"></div>');
										$('.happening-now .loading').show();
			                    		$('.happening-now .' + paneData.paneName).load(paneData.paneUrl, function() {$('.happening-now .loading').remove();});
			                		}
			            }
			});
		}
	},

/*	------------------------------------------------------------------------------------------
	IndieWIRE NEWS MODULE

	The news is pulled in when user scrolls down 200px.
	------------------------------------------------------------------------------------------ */
	indieNews: {
		ajaxURL: '/ajax/indiewire-news',
		loaded: false,
		init: function() {
			$('#indie-news .xhr-cont').append('<div class="loading"></div>');
		    $(window).scroll( function(e) {
		        if ($(window).scrollTop() > 200) {
		            if (!Snag.indieNews.loaded) {
		                $('#indie-news .xhr-cont').load(Snag.indieNews.ajaxURL);
		                Snag.indieNews.loaded = true;
		                $(this).unbind(e);
		            }
		        }
		    });	
		}
	},

/*	------------------------------------------------------------------------------------------
	Facebook Activity Feed (Friends on Snagfilms)

	Facebook activity loads when user scrolls down the page
	------------------------------------------------------------------------------------------ */

	fbActivity: {
		ajaxURL: '/ajax/facebookActivity.jsp',
		loaded: false,
		init: function() {
                    $('.friends .xhr-cont').append('<div class="loading"></div>');
		    $(window).scroll( function(e) {
		        if ($(window).scrollTop() > 100) {
		            if (!Snag.fbActivity.loaded) {
		                $('.friends .xhr-cont').load(Snag.fbActivity.ajaxURL);
		                Snag.fbActivity.loaded = true;
		                $(this).unbind(e);
		            }
		        }
		    });
		}
	},



/*	------------------------------------------------------------------------------------------
	NAVIGATION

	This controls the drop down menus of the navigation
	------------------------------------------------------------------------------------------ */
	nav: {
		init: function() {
			$('.navBar .nav > li, .profile-dropdown').hover(
				function() {
					var dd = $(this).find('div.dropdown');
					// checking dim the lights is necessary for IE
					if (dd.length > 0 && ($('#snag-dimmerBG').filter(":visible").length < 1) ) { 
						$(this).addClass('open');
						dd.show();
					}
				}, 
				function() { 
					$(this).removeClass('open');
					$(this).find('div.dropdown').hide();
				}
			);
            $('.dropdown .queue-populated li a').click(function(event){
                Snag.Tracking.GA.trackClick(event, "registration and profiles", "watch-q");
            });
		}
	},

/*	------------------------------------------------------------------------------------------
	MOVIE MATCHER
	
	------------------------------------------------------------------------------------------ */
	movieMatcher: {
        AJAX_URL: "/ajax/movie-matcher",
		FHB: {},
		init: function() {
			if ($('#movie-matcher').length > 0){
				this.FHB = new Snag.Utils.FilmHoverBox.Box(3);
				$('#movie-matcher').append('<div class="loading"></div>');
				Snag.movieMatcher.matcherInit();
			}
		},
		doCategoryRefresh: function(anchorObj) {
			Snag.movieMatcher.loading.show();
                        $('#xhr-result').load(Snag.movieMatcher.AJAX_URL + "?" + anchorObj.attr('data-filter') + " #xhr-wrap", function(){
                            Snag.movieMatcher.matcherInit();
                            Snag.movieMatcher.loading.hide();
                        });
		},
		loading: {
			show: function() {$('#movie-matcher .loading').show();},
			hide: function() {$('#movie-matcher .loading').hide();}
		},
		matcherInit: function() {
			// these need to be reset each time the ajax call is made
			$('#movie-matcher .nav .categories .selected').append('<span class="marker"></span>');
			$('#movie-matcher .nav .categories a').click(function(event) {
			                if (this.id != "mm-all-cats") {
                                event.preventDefault();
                                Snag.Tracking.GA.trackEvent('movie matcher', event.currentTarget.className == 'mm-tag' ? 'mm-sub-word' : 'mm-word');
                                Snag.Tracking.GA.trackEvent("movie matcher", "mm-click");
                                Snag.movieMatcher.doCategoryRefresh($(this));
                            }
                        });
			$('#movie-matcher .category-results ul.tabs').tabs('#movie-matcher .category-results div.panes > div', {
				tabs: 'li',
				current: 'selected'
			});
                        $('#movie-matcher .category-results ul.tabs li a').click(function(event) {
                            Snag.Tracking.GA.trackEvent('movie matcher', 'mm-nav');
                            Snag.movieMatcher.loading.show();
                            setTimeout( function() {Snag.movieMatcher.loading.hide();}, 300);
                        });
			$('#movie-matcher .results li').hover(
				function() {if (FixZIndexBugs) {$(this).css('z-index', '100');}Snag.movieMatcher.FHB.show(this);},
				function() {Snag.movieMatcher.FHB.hide(this);if (FixZIndexBugs) {$(this).css('z-index', '40');}}
			);
                        $('#movie-matcher .results li a')
                                .filter(function(){return $(this).parents(".queue").length == 0})
                                .click(function(event){
                            Snag.Tracking.GA.trackEvent(event, "movie matcher", "mm-click");
                            Snag.Tracking.GA.trackClick(event, "movie matcher", "mm-watch");
                            
                        });
                        $('#movie-matcher .results .more-btn').click(function(event){
                            Snag.Tracking.GA.trackEvent(event, "movie matcher", "mm-click");
                            Snag.Tracking.GA.trackClick(event, "movie matcher", "mm-more");
                        });
			if (FixZIndexBugs) {
				$('#movie-matcher .results li').css('z-index', '40');
			}
		}
	},


/*	------------------------------------------------------------------------------------------
	NEWSLETTER SIGNUP

	Used for the newsletter popup
	------------------------------------------------------------------------------------------ */
        newsletter: {
            init: function() {
                if ($('.newsletter').length) {
                    $('.newsletter').click(function(event){
                        event.preventDefault();
                        /*
                         * id attribute of clicked anchor maps to dynamic dom element names
                         * see newsletterPopup.jsp
                         */
                        frameWrapId = $(this).attr("id") + '-frame-wrap';
                        $('#' + $(this).attr("id") + '-frame').attr("src", "/newsletter.jsp");
                        $('#' + frameWrapId).fadeIn(500);
                    });
                }
            }
        },


/*	------------------------------------------------------------------------------------------
	PROFILE

	Used for the profile options when the user is logged in.
	------------------------------------------------------------------------------------------ */
	profile: {

		init: function() {
			if ($('.queueMod').length > 0 ) {
				Snag.ajaxLoad.setContainer(".queueMod");
				// Enable Profile Tabs
				$('.queueNav li').click( function(event) {event.preventDefault();Snag.profile.switchTab(this);} );

				this.reInit();
			}
		},
		reInit: function() {
			// These are items that need init each time an ajax load is done.
			$('.queueMod').append('<div class="loading"></div>');
			// Enable the hover Remove from your queue links (both the queue and activity feed links)
			var oLi = $('.queueMod .queue-list li, .queueMod .activity li');
			oLi.hover( function() {$(this).find('.close').show();},
			 		function() {$(this).find('.close').hide();});
			oLi.find('.close').click( function(event) {event.preventDefault();Snag.profile.remove(this);});
			// Enabale Pagination Tabs
			Snag.Utils.Pagi('.queueMod', function() {Snag.profile.reInit();});
			this.initTab();
		},
		initTab: function() {
			switch($('.queueNav li.selected')[0].className.replace(/[\s](selected)/gi, "")) {
				case 'tb-profile':
					// do something related to the profile
					break;
				case 'tb-queue':
					this.queue.init();
					break;
				case 'tb-activity':
					// do something related to the activity
					this.activity.init();
					break;
				case 'tb-manage':
					this.manage.init();
					break;
				case 'tb-settings':
					this.settings.init();
					break;
			}
		},
		switchTab: function(o) {
			var oLi = $(o);
			var oLoad = $('.queueMod .loading');

			$('.queueNav li').removeClass('selected');			// remove select class from tabs
			oLoad.show();										// Start Loading Spinner
			Snag.ajaxLoad.load(oLi.find('a')[0].href, function() {oLoad.hide();oLi.addClass('selected');Snag.profile.reInit();} );
		},
		togglePrivacy: function(o) {
                        var ajaxUrl = $(o).attr("data-url");
                        if (ajaxUrl.length > 0) {
                            ajaxUrl += $(o).is(':checked') ? 'off' : 'on';

                            $.post(ajaxUrl);
                        }
		},
		remove: function(o) {
			$.ajax({ 
				url: o.href,
				success: function() {
					var p = $(o).parents('li');
					p.append('<div class="loading"></div>');
					p.find('.loading').show();
					p.slideUp("slow", function() {p.remove();});
				}
			});
		},
	/*	------------------------------------------------------------------------------------------
		RECENT ACTIVITY - This is for the users view of their queue
		------------------------------------------------------------------------------------------ */
		activity: {
			init: function() {
				$('.activityToggle .clearAll .close').click( function(event) {event.preventDefault();Snag.profile.activity.clear(this.href);})

			},
			clear: function(u) {
				if (confirm("Are you sure you want to clear all of your activity?")) {
					$.ajax({
						url: u,
						success: function() {
							var q = $('.queueMod');
							q.find('.pagi').remove();
							q.find('.clearAll').remove(); 
							q.find('.activity').slideUp('slow', function() {$(this).remove();});
						}
					});
				} else {
					return false;
				}
			}
		},
	/*	------------------------------------------------------------------------------------------
		YOUR QUEUE - This is for the users view of their queue
		------------------------------------------------------------------------------------------ */
		//	NOTE: This is for the profile queue PAGE, which is different than the 
		//	other functions named queue.
		queue: {
			init: function() {
				Snag.Utils.UI.init();
				// This removes an item from your queue
				$('.queueMod .queue-list .close').click( function(event) {
					event.preventDefault();
					$(this).hide();
					Snag.queue.updateCounts(-1, true);
				});
                if (SNAG.loggedIn)  {
                    $('.queueMod .queue-list a')
                        .filter(function(){return $(this).attr('class') != 'close'})
                        .click( function(event) {
                            Snag.Tracking.GA.trackClick(event, "registration and profiles", "watch-q");
                    });
                }
			}
		},
	/*	------------------------------------------------------------------------------------------
		MANAGE PROFILE
		------------------------------------------------------------------------------------------ */
		manage: {
			init: function() {
				$('.edit-profile .cancel').click( function(e) {
					e.preventDefault();
					if (confirm("Cancel these changes \n\n Are you sure you want to cancel these changes?")) {
						$('.frm-manage-profile')[0].reset();
					}
				});
			}
		},
	/*	------------------------------------------------------------------------------------------
		MANAGE PROFILE
		------------------------------------------------------------------------------------------ */
		settings: {
			init: function() {
				$('.edit-profile .cancel').click( function(e) {
					e.preventDefault();
					if (confirm("Cancel these changes \n\n Are you sure you want to cancel these changes?")) {
						$('.frm-settings')[0].reset();
					}
				});
				$('.accounts .delete-account').click( function(e) {
					e.preventDefault();
					if (confirm("Are you sure you want to delete?\n\nYour profile, movie queue, and all activity associated with your account will be deleted. It's permanent -- there is no undo!\n(Note that any comments you've made with your Facebook account will remain on the site.)\n\nDon't worry though, you'll still be able to watch all the movies you want.")) {
                                                Snag.Tracking.GA.trackEvent('registration and profiles', 'delete-profile');
						$.post(e.currentTarget.href, function(data) {
                                                    FB.logout();
                                                    location.href = '/';
                                                });
					}
				});
			}
		}
	},

/*	------------------------------------------------------------------------------------------
	QUEUE - Generic handling for "Add to Queue" links throughout the site

	------------------------------------------------------------------------------------------ */
	queue: {
		init: function() {
			$('.queue a, a.queue').live('click', function(e) {
			    if (!$(this).hasClass('disabled')) {
			        e.preventDefault();Snag.queue.add(this);
			    } 
			});
		},
		add: function(o) {
		    var obj = $(o);
			if (SNAG.loggedIn)  {
			    var action = obj.attr("data-action");
			    var filmId = obj.attr("data-id");
			    obj.addClass('disabled');
                if (filmId.length > 0) {
                    $.get('/ajax/queue.jsp?a=' + action + '&id=' + filmId, function(){
                        if (action == "add") {
                            obj.attr('data-action', 'rem').html('Remove from Queue').addClass('remove');
                            Snag.queue.updateCounts( 1 );
                            Snag.Tracking.GA.trackEvent('registration and profiles', 'add-q');                            
                        } else {
                            obj.attr('data-action', 'add').html('Add to Queue').removeClass('remove');
                            Snag.queue.updateCounts( -1 );
                            Snag.Tracking.GA.trackEvent('registration and profiles', 'remove-q');
                        }
                        // check to see if on film page and if feature film was added or removed.
                        if ($('.video-lead-wrapper') && (obj.parents('.video-stats').length==1 || obj.parents('#panel-add').length==1)) {
                            // make sure the message changes to added on both places on the page
        					if (action == "add") {
                                $('.panel-add a.queue, .video-lead a.queue').attr('data-action', 'rem').html('Remove from Queue').addClass('remove');                      
                            } else {
                                $('.panel-add a.queue, .video-lead a.queue').attr('data-action', 'add').html('Add to Queue').removeClass('remove');
                            }
                        }
                        obj.removeClass('disabled');
                    });
                }
			} else {
				var q = obj.parent('.queue');
				if (q.length > 0 ) {
					obj.hide();
					q.append('<span class="queue-login">' + $('#queue-login').html() + '</span>');
					q.find('.queue-login .btn-fb').click( function(event) {
                                            Snag.fb.login(event);
                                            if (isFilmPage) {
                                                vid.player.pause();//pauses video
                                            }
                                        });
				}
			}
		},
		updateCounts: function(num, usersProfilePage) {
			var oTb = $('.nav-queue .tab b');
			var currCount = parseInt(oTb.html());
			num = num + currCount;
			num = (num >= 0) ? num : 0;
			$('.nav-queue .tab b').html(num);
			if (usersProfilePage) {
				$('.tb-queue b').html(num);
			}
		}
	},


/*	------------------------------------------------------------------------------------------
	RECIRCULATION MODULE

	The Carousel in the footer on most pages -- First load occurs via AJAX on scroll down
	------------------------------------------------------------------------------------------ */
	recirculation: {
		FHB: {},
		ajaxURL: "/ajax/footer-carousel",
		loaded: false,

		init: function() {
			if ($('.recirculation-module').length > 0) {
				$(window).scroll( function(e) {
					if ($(window).scrollTop() > 300) {
						if (!Snag.recirculation.loaded) {
							$('.recirculation-module .carousel').css('height', '153px');
							Snag.recirculation.loadCarousel(Snag.recirculation.ajaxURL);
							Snag.recirculation.loaded = true;
							$(this).unbind(e);
                                                        Snag.recirculation.initTracking();
						}
					}
				});
			}
		},

		// This re-init will happen every time the carousel is re-loaded
		reInit: function() {
			this.FHB = new Snag.Utils.FilmHoverBox.Box(7);
			this.hoverBubbleInit();
                        Snag.recirculation.initTracking();
		},
		// This re-init happens only when the tabs change
		tabReInit: function() {
			$('.recirculation-module .tabs a').click( function(e) {
				 	e.preventDefault();
					if (!$(this).parent('li').hasClass('selected')) {
						Snag.recirculation.loadCarousel(Snag.recirculation.getQueryString(this.href));
					} 
			});
			$('.recirculation-module .pagination a').click( function(e) {
					e.preventDefault();
					var oDiv = $(this).find('div');
					if (!oDiv.hasClass('disabled')) {
						Snag.recirculation.loadCarousel(Snag.recirculation.getQueryString(this.href));
					}
			});
			Snag.recirculation.reInit();
		},
		loadCarousel: function(url) {
			$('.recirculation-module .carousel').append('<div class="loading"></div>');
			$('.recirculation-module .carousel .loading').show();
			Snag.ajaxLoad.load(url, function() {Snag.recirculation.tabReInit();}, ".recirculation-module .carousel");
		},
		getQueryString: function(url) {
			return this.ajaxURL + "?" + url.split("?")[1];
		},
		// Called everytime an AJAX call is done to re-init the hoverbubbles
		hoverBubbleInit: function() {
			$('.recirculation-module .items li').hover(
					function() {Snag.recirculation.FHB.show(this);},
					function() {Snag.recirculation.FHB.hide(this);}
			);
		},
                initTracking: function() {
                        $('.recirculation-module .fc-q a').click(function(event){
                            Snag.Tracking.GA.trackClick(event, "registration and profiles", "watch-q");
                        });
                }
	},


/*	------------------------------------------------------------------------------------------
	SOCIAL BUZZ

	This module will load it's content after page load via AJAX. 
	------------------------------------------------------------------------------------------ */
	buzz: {
		ajaxURL: '/ajax/social-buzz',
		transSpeed: 500,		// Speed of transition between slides
		autoSpeed: 10000,		// delay between auto roatation
		loaded: false,

		init: function() {
			if ($('.buzz').length > 0) {
				// Add container element to hold the buzz
				$('<div class="scrollable-buzz"></div>').insertBefore('.buzz .fb-twit').append('<div class="loading"></div>');
				$('.buzz .loading').show();
				// Wait for page scroll to load
				$(window).scroll( function(e) {
					if ($(window).scrollTop() > 200) {
						if (!Snag.buzz.loaded) {
							Snag.ajaxLoad.load(Snag.buzz.ajaxURL, function() {
                                                            Snag.buzz.initScrollable();
                                                            $('.buzz a').click(function(event) {
                                                                event.currentTarget.target = '_blank';
                                                                Snag.Tracking.GA.trackEvent("modules", "buzz");
                                                            });
                                                        }, ".scrollable-buzz");
							Snag.buzz.loaded = true;
							$(this).unbind(e);
						}
					}
				});
			}
		},	
		initScrollable: function() {
			// upon return of the buzz, make it autoscroll
			$('.scrollable-buzz').scrollable({circular: true, vertical: true, speed: this.transSpeed}).autoscroll({interval: this.autoSpeed});
		},
		populateBuzz: function(sHTML) {
			$('.scrollable-buzz').html(sHTML);
			this.initScrollable();
		}
	},

/*	------------------------------------------------------------------------------------------
	SUBMIT A FILM

	"Submit a Film" editorial module; needs click tracking
	------------------------------------------------------------------------------------------ */
        submitFilm: {
            init: function() {
                $('.subFilm a').click(function(event){
                   Snag.Tracking.GA.trackClick(event, "modules", "submit-film");
                });
            }
        },


/*	------------------------------------------------------------------------------------------
	TEAM

	Team related JS
	------------------------------------------------------------------------------------------ */
	team: {
		TextShow: "More About",
		TextHide: "Less About",

		init: function() {
			$('.team .more').toggle(
				function() {
					var o = $(this);
					o.siblings('.more-info').slideToggle('slow');
					o.find('span').html(Snag.team.TextHide);
					o.addClass('open-arrow');
				},
				function() {
					var o = $(this);
					o.siblings('.more-info').slideToggle('slow');
					o.find('span').html(Snag.team.TextShow);
					o.removeClass('open-arrow');
				}
			);
		}
	},

/*	------------------------------------------------------------------------------------------
	YOU'VE BEEN WATCHING
	
	You've been watching module on main page needs to be hiden and a cookie set when the user
	closes it. The cookie is checked server side.
	------------------------------------------------------------------------------------------ */
	ybw: {
		cookieName: "snag-ybw-hide",
		init: function() {
			if ($('.ybw').length > 0) {
				$('.ybw .hide').click(function(event) {
				        event.preventDefault();
				        Snag.Utils.cookie.set(Snag.ybw.cookieName, "true");
				        $('.ybw').remove();
				});
                                $('.ybw li a').click(function(event) {
                                    Snag.Tracking.GA.trackClick(event, "registration and profiles", "been-watching");
                                });
			}
		}
	},

/*	------------------------------------------------------------------------------------------
	UTILITIES

	Utility Functions Used thought out
	------------------------------------------------------------------------------------------ */	
	Utils: {
		// Currently the types of FHB are designated by numbers.
		// 3: Designates the 3 column by two row configuration used in the movie matcher and some filmanthropy pages
		// 5: Designates the block view of search and browse pages - with ad
		// Everthing else is generic
		// This may need to change in the future.
		FilmHoverBox: {
			Box: function(type) {
				// Check for global container to hold hover box and create if it doesn't exist.
			/*	if (!Snag.Utils.FilmHoverBox.FHB) {
					if (!($('#film-hvr-bx'))) {
						console.long('need to create film hvr box');
						$('body').append('<div id="film-hvr-bx"></div>');
					}
					Snag.Utils.FilmHoverBox.FHB = $('#film-hvr-bx');
				} */

					// Asign Types of layout the hover box is going to be associated with.
					this.type = type;
			},

			FHB: null,
			offsets: {
				topArrow: 30,
				bottomArrow: 30,
				right: 35,
				left: 35,
				top: 20, 
				side: 20
			},
			setPosition: function(arrow, o, fhb) {
				var cssObj = {
					'left': Snag.Utils.FilmHoverBox.findLeft(arrow, o),
					'top': Snag.Utils.FilmHoverBox.findTop(arrow, o)
				}
				fhb.css(cssObj);
			},
			findLeft: function(arrow, o) {
				if (arrow.indexOf("upper") > -1 || arrow.indexOf("lower") > -1) {
					if(arrow.indexOf("right") > -1) {
						return -(o.find('.film-hvr-bx').width() - o.find("img").width() - Snag.Utils.FilmHoverBox.offsets.right);
					} else if (arrow.indexOf("left") > -1 ) {
						return -Snag.Utils.FilmHoverBox.offsets.left;
					} else {
						return -(o.find('.film-hvr-bx').width()/2 - o.find("img").width()/2);
					}
				} else {
					if(arrow.indexOf("right") > -1) {
						return -(o.find('.film-hvr-bx').width() - Snag.Utils.FilmHoverBox.offsets.side);
					} else {
						return o.find("img").width() - Snag.Utils.FilmHoverBox.offsets.side;
					}
				}
			},
			findTop: function(arrow, o, fhb) {
				if (arrow.indexOf("upper") > -1) {
					return o.find("img").height() + Snag.Utils.FilmHoverBox.offsets.topArrow;
				} else if (arrow.indexOf("lower") > -1) {
					return -(o.find('.film-hvr-bx').height() + Snag.Utils.FilmHoverBox.offsets.bottomArrow);
				} else {
					return Snag.Utils.FilmHoverBox.offsets.top;
				}	
			}
		}, // end FilmHoverBox
		// Fixes places that break due to z-index oddities in IE7
		FixZIndexBugs: function() {

		},
		cookie: {
			set: function(name, value, days) {
				if (days) {
					var date = new Date();
					date.setTime(date.getTime()+(days*24*60*60*1000));
					var expires ="; expired="+date.toGMTString();
				}
				else var expires = "";
				document.cookie = name + "=" + value + expires + "; path=/";	
			},
			get: function(name) {
				var c = document.cookie.split(/[; ]+/);
				for (var i=0; i < c.length; i++) {
					var cName = c[i].split("=", 1);
					if (cName == name) {
						return c[i].slice(c[i].indexOf("=")+1);
					}
				}
				return null;
			} 
		}, // end cookie

		/* Pagination */
		Pagi: function(container, cb) {
			cont = container;
			callback = cb,
			$(cont + ' .pagi a').click( function(event) { 
					event.preventDefault();
					if (!$(this).parent('li').hasClass('disabled')) {
						var oLoad = $(cont + ' .loading');
						oLoad.show();
						Snag.ajaxLoad.load($(this)[0].href, function() { 
							oLoad.hide(); 
							return callback(); 
						});
						Snag.Utils.ScrollTop();
					}
			});
		},

		/* Scroll to where the anchor tag named top is  or where the optional parameter is 
			(for now this only goes up, but could be made smarter to go up or down or not move at all) */
		ScrollTop: function(attrName) {
			var refreshTop = (attrName) ? $('a[name=' + attrName + ']').offset().top : $('a[name=top]').offset().top;
			var pageY = window.pageYOffset ? window.pageYOffset : document.documentElement.scrollTop;
			if (pageY > refreshTop) {
				$('html, body').animate({scrollTop:refreshTop}, 'slow');
			}
		},

		/* UI enhancements to the look and feel of the UI elements made with CSS and JavaScript */
		UI: {
			init: function() {
				if ($('.ui-select').length > 0) {
					Snag.Utils.UI.select.init();
				}
				// This is for the messaging dialogs
				$('.message').delay(5000).hide('slow', function() {$(this).remove();})
			},
			select: {
				init: function(parent) {
					var uiSelect = (parent) ? $(parent + ' .ui-select') : $('.ui-select');
					var blnContinue = true;
			
					// Set the widths
					uiSelect.each ( function(index) { 
						if ($(this).siblings('.frm-select').length < 1) {
							$(this).after('<div class="frm-select"><div class="filter"><h4></h4><span class="drop-arrow"></span></div></div>');
							var frmSelect = $(this).siblings('.frm-select');
							var w = uiSelect.eq(index).outerWidth();
							if (w == 0) {
								w = parseInt(uiSelect.eq(index).css('width'))
							}
							var f = frmSelect;
							var h4 = f.find('h4');
							Snag.Utils.UI.select.populateDD(frmSelect, this);
							h4.width(parseInt(w) - 35 - 31); // minus the padding, minus the dd button 
							f.find('.dropdown').css({/*'width': w - 10,*/'min-width': w,
														'left': h4.offset().left - h4.offsetParent().offset().left});
						} else {
							blnContinue = false;
						}					
					});
					if (blnContinue) {
						var frmSelects = (parent) ? $(parent + ' .frm-select') : $('.frm-select');
						// Make clicks on the faux drop down change the data in the actual drop down
						frmSelects.find('.dropdown li').click( function() {Snag.Utils.UI.select.doDDIClick(this);});
						frmSelects.click( function() {$(this).find('.dropdown').toggle();});
						frmSelects.mouseleave( function() {Snag.Utils.UI.select.hideMenu(this);});

                        // For "jump to" dropdowns, bind onchange to URL redirects
                        if (uiSelect.hasClass('jump')) {
                            uiSelect.change( function() {
                                var url = $(this).find('option').filter('option:selected').val();                               
                                if (url.length > 0) {
                                    location.href = url;
                                }
                            });
                        }
					}
					uiSelect.hide();
				},
				showMenu: function(o) {
					$(o).find('.dropdown').show();
				},
				hideMenu: function(o) {
					$(o).find('.dropdown').hide();
				},
				populateDD: function(oForm, oDD) {
					var tSelected = "";
					var sHTML = "";
					var blnStars = (oDD.id == "filter-rating") ? true : false;

					$(oDD).children('option').each( function(index) { 
						sHTML += "<li>" + this.text + "</li>";
						if (this.selected || index == 0) {tSelected = this.text;}
					});
					oForm.find('h4').html((blnStars) ? Snag.Utils.UI.makeStars(tSelected) : tSelected);
					oForm.append('<ul class="dropdown">' + ((blnStars) ? Snag.Utils.UI.makeStars(sHTML) : sHTML) + '</ul>');
				},
				doDDIClick: function(o) {
					var o = $(o);
					var oFrmSlt = o.closest('.frm-select');
					var oLi = oFrmSlt.prev('.ui-select')[0].options[o.index()];

					oLi.selected = true;
					oFrmSlt.prev('.ui-select').change();		// trigger the seletion change manually
					oFrmSlt.find('h4').html(Snag.Utils.UI.makeStars(oLi.text));
				},
				resetToDefault: function(id) {
					slt = $(id);
					slt[0].options[0].selected = true;
					slt.siblings('.frm-select').find('h4').html(slt[0].options[0].text);
				}
			},
			makeStars: function(s) {
				// Turn the text "X Stars" into a pictorial representation of the stars for the children of o.
				var regEx = /(([12345])\sstars)/ig;
				return s.replace(regEx, '<span class="stars s$2"><span class="alt">$1</span></span>');

			}
		}, // end UI

                // Support for sponsored ad skins;  e.g., page background image takeovers, etc.
                AdSkin: {
                    setBg: function(src) {
                        $("body").css("background-image", "url('"+ src + "')");
                        $("body").addClass("sponsored");
                    }
                } // end AdSkin
	}, // end utils

        Tracking: {
            // Google Analytics event tracking
            // http://code.google.com/apis/analytics/docs/tracking/eventTrackerGuide.html
            GA: {
                trackClick: function(evt, category, action, label, value) {
                    evt.preventDefault();
                    Snag.Tracking.GA.trackEvent(category, action, label, value);
                    setTimeout('document.location = "' + evt.currentTarget.href + '"', 100);
                    
                },
                trackEvent: function(category, action, label, value) {
                    _gaq.push(['_trackEvent', category, action, label, value]);
                }
            } // end GA
        } // end Track
} // End Snag

// These are the prototype functions for the FilmHoverBox
Snag.Utils.FilmHoverBox.Box.prototype.show = function(o) {
	var obj = $(o);
	var fhb = obj.find('.film-hvr-bx');

	// if this hover box hasn't been displayed, calculate orientation and position.
	if (fhb[0].className.split(" ").length < 3) {
		var i = obj.index();
		var cn = this.whichArrow(i);
		if (obj.css("position") == "static") {
			obj.css("position", "relative");
		}
		fhb.addClass(cn);
		Snag.Utils.FilmHoverBox.setPosition(cn, obj, fhb);
	}
	FHBtimeout = setTimeout(function() {fhb.show()}, 750);
}
Snag.Utils.FilmHoverBox.Box.prototype.hide =  function(o) {
	clearTimeout(FHBtimeout);
	$(o).find('.film-hvr-bx').hide();
}
// Determine the class that needs to be applied to put the arrow in the right location
Snag.Utils.FilmHoverBox.Box.prototype.whichArrow = function(iIndex) {
	var pos = ["left", "center", "right"];
	var t = this.type;
	if (t == 3) {
		return ((parseInt(iIndex/3) == 0) ? "upper-" : "lower-") + pos[(iIndex % 3)];
	} else if (t == 5) {
		if (iIndex < 6) {
			return pos[0];
		} else {
			return (((iIndex-6) % 5) <= 2) ? pos[0] : pos[2];
		}
	} else {
		// furthest to the left has arrow on the left, furthest to the right has arrow to the right, all inbetween have arrow in center
		return "lower-" + (((iIndex % t) == 0) ? pos[0] : (((iIndex % t) == (t -1)) ? pos[2] : pos[1]));
	}
}

/* * * * * * * * * * * * * * * * * * * * * * * *

			Do this on document load
		
 * * * * * * * * * * * * * * * * * * * * * * * */
$(document).ready(function() {
	if ($.browser.msie && parseInt($.browser.version) < 8) {FixZIndexBugs = true;}
	Snag.nav.init();
	Snag.Utils.UI.init();					// modifies the look and feel of form/UI elements 
	Snag.fb.init();
	$('input, textarea').placeholder();		// Init for placeholder/ghost text
	Snag.queue.init();
	Snag.leadCarousel.init();
	Snag.ybw.init();
	Snag.movieMatcher.init();
        Snag.fbActivity.init();
        Snag.connect.init();
	Snag.recirculation.init();				// footer carousel
	Snag.now.init();
	Snag.buzz.init();
	Snag.film.init();
	Snag.featCat.init();
	Snag.filmanthropy.init();
        Snag.newsletter.init();
	if ($('.browse').length > 0) {Snag.browse.init()};
	if ($('.team').length > 0) {Snag.team.init()};
	Snag.profile.init();
	Snag.indieNews.init();
	Snag.addThis.init();
        Snag.submitFilm.init();
});
