/* global variables */
var mdbTimer = 1;
var scriptPath;
var ajaxErrorMessage = "Our apologies. I have a bad feeling about this."
hpCarousel = null;
var debugMsgs = false;

/* script versions to use */
var jQsimpleModal = "jquery.simplemodal.1.4.1.min.js";
var jQhint = "jquery.hint.pack.js";
var jQeasing = "jquery.easing.pack.js";
var jQtableSorter = "jquery.tablesorter.pack.js";
var jQhoverIntent = "jquery.hoverIntent.min.js";
var jQCarousel = "jquery.jcarousel.pack.js";
var jQPlugins = "plugins.js";
var sCode = "s_code.js";
// Used by functions WriteToContainer and GetContainerContent as a map of "Container IDs" to "Container Contents".
var CONTAINER_CONTENTS = [];

$(document).ready(function() {
    /* set scriptPath */
    scriptPath = getScriptURL();

    /* add specificity */
    addBrowserClass();

    /* add browser info on the page */
    // browserDiagnostics();

    /* lazy scripts */
    $.ajaxSetup({ cache: true });
    //$.getScript(scriptPath + jQeasing);
    //$.getScript(scriptPath + jQPlugins);

    /* enable input box hints */
    if ($.hint) {
        $('input[title!=""]').hint();
    } else {
        $.getScript(scriptPath + jQhint, function() {
            $('input[title!=""]').hint();
        });
    }

    /* breadcrumb truncation */
    if ($.ellipsis) {
        $("#breadcrumb").ellipsis();
        $("#breadcrumb").css("visibility", "visible");
    } else {
        $.getScript(scriptPath + jQPlugins, function() {
            $("#breadcrumb").css("visibility", "visible");
            $("#breadcrumb").ellipsis();
            $("#breadcrumb").show();
        });
    }

    /* make tables sortable */
    if (($(".people .sortable").size() > 0) || ($(".movie .sortable").size() > 0)) {
        // check to see if function exists 
        if ($.tablesorter) { // Already exists
            $(".sortable").tablesorter({
                widgets: ['zebra'],
                textExtraction: textExtract
            });
        } else {
            // dynamically load script, then execute after callback
            $.getScript(scriptPath + jQtableSorter, function() {
                $(".sortable").tablesorter({
                    widgets: ['zebra'],
                    textExtraction: textExtract
                });
            });
        }
    }

    /* make tables sortable */
    if ($(".buzzBin-archive .sortable").size() > 0) {
        // check to see if function exists 
        if ($.tablesorter) { // Already exists
            $(".buzzBin-archive .sortable").tablesorter({
                widgets: ['zebra']
            });
        } else {
            // dynamically load script, then execute after callback
            $.getScript(scriptPath + jQtableSorter, function() {
                $(".buzzBin-archive .sortable").tablesorter({
                    widgets: ['zebra']
                });
            });
        }
    }

    /* dynamically load modal scripts */
    if ($("#modalPlayer").size() > 0) {
        if ($.modal) {
            // do nothing
        } else {
            $.getScript(scriptPath + jQsimpleModal);
        }
    }

    /* make tabs */
    // first check to see if tabContent is disabled
    if ($(".tabContent").size() > 0) {
        var selectedTab = $(".tabContent").index($(".tabContent.selected"));
        // in case nothing is selected
        if (selectedTab == -1) { selectedTab = 0; }
        // render tabs with selected option
        $(".tabs").tabs({ selected: [selectedTab] }, { fx: { height: 'toggle', opacity: 'toggle'} }).show();

        // now disable the other tab
        if ($(".tabContent").hasClass("disabled")) {
            var disabledTab = $(".tabContent").index($(".tabContent.disabled"));
            $(".tabs").tabs("disable", [disabledTab]);
        }
    }

    /* show segment photos */
    if ($(".segmentSelections a").size() > 0) {
        segmentSubControl(".segmentSelections a", "ul", ".segment");
    }

	/* initialize layer box */
    if ($("#profileLayerBox").size() > 0) {
        if ($.hoverIntent) { // Already exists
            enableLayerBox(".profileTrigger", "#profileLayerBox", 20, 45);
        } else {
            $.getScript(scriptPath + jQhoverIntent, function() {
                enableLayerBox(".profileTrigger", "#profileLayerBox", 20, 45);
            });
        }
    }

    /* initialize any accordions */
    if (!($.browser.msie && $.browser.version.substr(0, 3) == "6.0")) {
        if ($("#accordion").size() > 0) {
            $("#accordion").accordion({
                collapsible: false,
                autoHeight: false,
                active: 0,
                animated: 'EaseInOutExpo'
            });
        }
    }

    /* initialize burning question */
    if ($("#burningQuestion").size() > 0) {
        burningQuestion();
    }

    /* initialize movie times location box */
    if ($("#changeLocationBox").size() > 0) {
        $("#locationSet").bind("click", function(e) {
            e.preventDefault();
            var clb = $("#changeLocationBox");
            $(clb).appendTo("form");

            var locOffset = $(this).offset();
            
            if ($(this).prev().text() == "Near:") {
            	clb.css("left", locOffset.left +17).css("top", locOffset.top + 24);	
            } else {
            	clb.css("left", locOffset.left-15).css("top", locOffset.top+24);	
            }
            
            if ($.browser.msie) {
                clb.show();
            } else {
                clb.fadeIn();
            }
            return false;
        });

        enableLocationBox();
    }

    /* initialize global search */
    if ($("#globalSearch .inputString").size() > 0) {
        var currentSelection = 0;
        var currentUrl = '';
        var goFetch;
        var globalTimer;

        $("#globalSearch .inputString").focus(function() {
            $(this).addClass("focused");
        });
        $("#globalSearch .inputString").blur(function() {
            $(this).removeClass("focused");
            $("#suggestions").fadeOut();
        });

        function navigate(direction) {
            // first check if autosuggest is visible
            if ($("#suggestions:visible")) {
                // Check if any of the menu items is selected
                var lastSelected = $("#searchresults .selected");
                var nextSelected = "";

                if (direction == 'up') {
                    lastSelected = $("#searchresults .selected");
                    nextSelected = lastSelected.prev(".gsItemSelect");
                    if (nextSelected.size() == 0) {
                        // check to see if there's another
                        nextSelected = lastSelected.prev().prev(".gsItemSelect");
                    }
                } else if (direction == 'down') {
                    if (lastSelected.size() == 0) {
                        nextSelected = $("#searchresults .gsItemSelect:first");
                    } else {
                        nextSelected = lastSelected.next(".gsItemSelect");
                        if (nextSelected.size() == 0) {
                            // check if there's another
                            nextSelected = lastSelected.next().next(".gsItemSelect");
                        }
                    }
                }

                if (nextSelected.size() == 1) {
                    lastSelected.removeClass("selected");
                    nextSelected.addClass("selected");
                }
            }
        }

        $("#globalSearch .inputString").bind("keydown keyup", function(event) {
            window.clearTimeout(goFetch);
            $("#searchForm .ajaxLoad").show();
            globalTimer = setTimeout('$("#searchForm .ajaxLoad").hide()', 500);

            if ($("#globalSearch .inputString").hasClass("focused")) {
                var selectionItems = $(".gsItemSelect");

                switch (event.keyCode) {
                    case 40:
                        if (event.type == "keyup") {
                            navigate("down");
                        }
                        break;
                    case 38:
                        if (event.type == "keyup") {
                            navigate("up");
                        }
                        break;
                    case 37: // do nothing	
                        break;
                    case 39: // do nothing  	
                        break;
                    case 13:
                        event.stopPropagation();
                        event.preventDefault();

                        event.returnValue = false;
                        event.cancel = true;
                        event.cancelBubble = true;                       
                        
                        if (event.type == "keydown") {
                            if (($("#globalSearch .inputString").val()) == "") {
                                $("#globalSearch .search").click();
                            } else {
                                if ($("#searchresults .selected").size() > 0) {                                	
                                	/* puts search value into global search - old endeca way */
                                    //$("#globalSearch .inputString").val($("#searchresults .selected .searchheading").text());
                                    
                                    /* re-focus and then click */
                                    $("#searchresults .selected").focus();
                                    window.location.replace($("#searchresults .selected").attr("href"));                                    
                                } else {
                                	$("#globalSearch .search").click();                                	
                                }                                
                            }
                        }
                        break;
                    case 8: //backspace
                        if ($("#globalSearch .inputString").val().length < 3) {
                            $("#suggestions").fadeOut();
                        } else {
                            goFetch = window.setTimeout(function() { lookup(event.target.value, $(event.target).attr("servername")); }, 100);
                        }
                        break;
                    case 46: //delete
                        if ($("#globalSearch .inputString").val().length < 3) {
                            $("#suggestions").fadeOut();
                        } else {
                            goFetch = window.setTimeout(function() { lookup(event.target.value, $(event.target).attr("servername")); }, 100);
                        }
                        break;
                    default:
                        goFetch = window.setTimeout(function() { lookup(event.target.value, $(event.target).attr("servername")); }, 100);
                }
            } else {
                return;
            }
        });
    }

    /* initialize suggestions positioning */
    if ($("#suggestions").size() > 0) {
        $("#suggestions").appendTo("body");
        var gsOffset = $("#globalSearch .searchBox").offset();
        $("#suggestions").css("left", gsOffset.left + 16).css("top", gsOffset.top + 38);
    }

    /* initialize the movieList carousel */
    if ($('#movieListCarousel').size() > 0) {
        if ($.jcarousel) {
        	var wssString = $('#movieLists #tabsMovieList a').attr("data-wss-arrow");
            movieListCarousel(wssString);
            $("#movieListCarousel").css("visibility", "visible");
        } else {
            $.getScript(scriptPath + jQCarousel, function() {
            	var wssString = $('#movieLists #tabsMovieList a').attr("data-wss-arrow");
                movieListCarousel(wssString);
                $("#movieListCarousel").css("visibility", "visible");
            });
        }
    }


    /* on homepage, dynamically load movie lists */
    $(".homePage #tabsMovieList li a").click(function(e) {
        var htmlCopy;
        var wssString = $(this).attr("data-wss-arrow");
        e.preventDefault();
        if ($(this).hasClass("selected")) {
            // do nothing
        } else {
            $("#tabsMovieList li a").removeClass("selected");
            $(this).addClass("selected");

            // reset carousel back to starting point otherwise new items load offset
            hpCarousel.reset();

            $("#movieListCarousel").load($(this).attr("href"), function() {
                htmlCopy = $("#movieListCarousel p");
                $("#movieLists > p").remove();
                $(".jcarousel-skin-homepage").after(htmlCopy);
                movieListCarousel(wssString);

                // fix for safari
                $(".safari .jcarousel-next").removeClass("jcarousel-next-disabled").removeClass("jcarousel-next-disabled-horizontal").attr("disabled", "false");
            });
        }
    });

    /* append RSS link inside sharethis for layout purposes TT #101422 */
    $("div.sharethis").append($("a[name=shareRSS].chicklet"));

    /* expandList */
    $("#searchResults .expandList a").live("click", function(e) {
        e.preventDefault();

        var ajaxLoader = "<div class='expandList'><img class='ajaxLoad' alt='Searching indicator' src='http://images.fandango.com/r2.1.8.4/MDCSite/images/global/shim.gif' style='display: block;' /></div>";
        $(ajaxLoader).insertBefore("#searchResults .sharethis");

        $(document).ajaxStart(function() {
            $(ajaxLoader).show();
        }).ajaxStop(function() {
            $(ajaxLoader).hide();
        });

        ReportToWss($(this).parent().attr("name"));

        $.ajax({
            url: $(this).attr("data-ajax-href"),
            cache: false,
            success: function(html) {
                $("#searchResults .expandList").remove(); // remove pre-existing expand link
                $(html).appendTo($(".resultsGroup:last"));
                $("#searchResults .expandList").insertBefore("#searchResults .sharethis");
                $(".resultsGroup .results").fadeIn();
                enableMoviePopup("#searchResults .results");
            }
        });
        return false;
    });

    /* calendar switch */
    $("#newUpcomingCalendar .tabsFancy li a").click(function(e) {
        var clicked = $(this).parent().index();
        e.preventDefault();
        $("#newUpcomingCalendar .tabsFancy li a").removeClass("selected");
        $(this).addClass("selected");
        $("#newUpcomingCalendar .month").removeClass("selected").animate({
            opacity: 0
        }, 200);
        $("#newUpcomingCalendar .month").eq(clicked).animate({
            opacity: 1
        }, 500).addClass("selected");
        return false;
    });

    /* expandList - CSM update */
    $(".expandToggle a").live("click", function(e) {
        e.preventDefault();

        function toggle(thisEl) {
            $(thisEl).toggleClass("more");
            $(thisEl).siblings("a").toggleClass("more");
        }

        var hiddenContent = $(e.target).parents(".expandToggle").siblings(".hiddenContent");
        var clicked = this;

        if (!hiddenContent.hasClass("show")) {
            hiddenContent.fadeIn("slow", function() {
                hiddenContent.addClass("show");
                toggle(clicked);
            });
        } else {
            hiddenContent.fadeOut("fast", function() {
                hiddenContent.removeClass("show");
                toggle(clicked);
            });
        }

        return false;
    });

    /* force page reload on trailers search Clear*/
    $(".trailers .searchClear").click(function(e) {
        e.preventDefault();
        $("#trailerSearchInput").val("");

        var newURL = $(this).attr("href").replace("#trailers", "?ord=" + (new Date()).getTime() + "#trailers");
        window.location = newURL;

        return false;
    });


    /* add focus/blur for multi-browser support */
    $("#trailerSearchInput").focus(function() {
        $(this).addClass("focused");
    });
    $("#trailerSearchInput").blur(function() {
        $(this).removeClass("focused");
    });

    /* trailers search ajax */
    $("#trailerSearchSubmit").bind("click", function(e) {
        e.preventDefault();
        if (($("#trailerSearchInput").val() == "Search for trailers") || ($("#trailerSearchInput").val() == "")) {
            return false;
        } else {
            // show search indicator
            $(".trailers .searchBoxMini .ajaxLoad").show();
            // display results
            $("#trailerSearchResults").slideUp(500, function() {
                $(this).html(searchTrailers($("#trailerSearchInput").val(), $(e.target).attr("servername"))).fadeIn();
                $("#SortTitle, #SortDate").removeAttr("href").addClass("disabled").click(function() { return false; }); // disable sort
                $(".sort img").removeAttr("class").parent().removeClass("selected"); // disable sort                                        
                $(".trailers .searchBoxMini .ajaxLoad").hide(); // hide search indicator
                $(".trailers .searchClear").show(); // show clear button
            });
        }
    });

    // bind the enter key for the input box
    $("#trailerSearchInput").bind("keydown keyup", function(event) {
        if ($("#trailerSearchInput").hasClass("focused") || $("#trailerSearchInput:focus")) {
            if (event.keyCode == 13) {
                event.stopPropagation();
                event.preventDefault();
                event.returnValue = false;
                event.cancel = true;
                event.cancelBubble = true;
                $("#trailerSearchSubmit").click();
            }
        }
    });

    // Comments - set up abuse reporting AJAX 
    $(".reportcomment").click(function() {
        $(this).unbind().bind('click', function() { return false; });
        $(this).parent().addClass("flagged");

        var id = $(this).attr("keyword");
        var serverName = $("#CommentMainDiv").attr("servername");
        var ajaxUrl = serverName + "/ajax.aspx?aop=CommentOperation&op=ReportAbuse&keyword=" + id + "&ord=" + date.getHours() + date.getMinutes() + date.getSeconds();

        $.get(ajaxUrl, function(data) {
            // $('#commentsAjaxResult').html(data);
        });
        $(this).children("img").attr("alt", "Comment Flagged").attr("title", "Comment Flagged");

        return false;
    });

    // If we have a user action, scroll to the results
    if ($(".commentFormThanks").length > 0 || $("#commentFormPostError").length > 0) {
        scrollTo("#CommentMainDiv", -100);
    }

    // Set up comment character counter
    if ($(".commentsViewer_CommentText").length > 0) {
        $(".commentsViewer_CommentText").keyup(function(event) {
            var maxChars = $("#commentLabelMaxChars").attr("maxchars");
            var currentChars = $(this).val().length;
            if (!isNaN(maxChars) && !isNaN(currentChars)) {
                $("#commentLabelMaxChars").html("Characters Remaining: " + Math.max(0, maxChars - currentChars));
            }
        });

        // Trigger the event to refresh the label
        $(".commentsViewer_CommentText").keyup();
    }

    // Automatically scroll to a section specified by a passed parameter
    var scrollToParameter = getParameterByName("scrollTo");
    switch (scrollToParameter) {
        case "comments":
            scrollTo("#CommentMainDiv");
            break;
    }

    // Prevent any forms on the page from being submitted twice
    $("form").submit(function() {
        $(this).submit(function() {
            return false;
        });
        return true;
    });

    // movietimes content
    $(".addedContent .reveal").hover(function() {
        $(this).stop().animate({
            width: '138px'
        }, 500, 'easeInOutCirc');
    }, function() {
        $(this).stop().animate({
            width: '45px'
        });
    });
	
	// enable slideshow
	if ($("#slideShow").length > 0) {
		enablePhotoViewer("#slideShow");
	}
	
	// enable movie popup
	if ($("#searchResults .results textarea").length > 0) {
		// check to see if textarea exists 	
		enableMoviePopup("#searchResults .results");	
	}
	
	// for movie news dropdown lists
	$("#frameNav #articleNav > li.sFish").hoverIntent(function() {
		var numColumns = 3;	
		createTableList(this, numColumns);
		$("#menuTable").animate({height: 'show',opacity:1},"normal","easeOutExpo",function(){}).css("display","block");				
	}, function() {		
		$("#menuTable").animate({height: 'hide',opacity:'hide'},"fast");
		removeTableList();
	}); 
	
	if ($.browser.msie && $.browser.version.substr(0, 3) == "7.0") {
		if ($("#frameNav").length > 0) {
			$(function() {
				var zIndexNumber = 1000;
				$('div').each(function() {
					$(this).css('zIndex', zIndexNumber);
					zIndexNumber -= 10;
				});
				$("#topMascot").css("z-index",1000);
			});						
		}
	}
	
	// load disqus dynamically
	if ($("#disqus_thread").length > 0) {
		$(window).bind('scroll', checkScrollingForDisqus); 
		checkScrollingForDisqus();	
	}	
});

// Write to firefox console if we have one
function log(text) {
    if (typeof (console) != "undefined" && debugMsgs) {
        console.debug(text);
    }
}

// Implement the percentEncode functionality, which is the javascript 'escape' function plus 4 additional special characters
function percentEncode(uri) {
    return escape(uri).replace(/\+/g, '%2B').replace(/\//g, '%2F').replace(/@/g, '%40').replace(/\*/g, '%2A');
}

// Animated scroll to the passed object
function scrollTo(selector, optionalOffset) {
    var targetOffset = $(selector).offset().top;
    if (!isNaN(optionalOffset))
        targetOffset += optionalOffset;
    $('html,body').animate({ scrollTop: targetOffset }, 500);
}

// Return the value for the specified parameter
function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.href);
    if (results == null)
        return "";
    else
        return decodeURIComponent(results[1].replace(/\+/g, " "));
}

/**
* searchTrailers
* - returns markup for Trailers Search/Sort
*/
function searchTrailers(inputString, serverName) {
    // only allow alphanumeric and spaces
    if (inputString.match(/[^a-zA-Z0-9\-\+\&\.\,\:\!\?\' ]/g)) {
        inputString = inputString.replace(/[^a-zA-Z0-9\-\+\&\.\,\:\!\?\' ]/g, '');
    }

    var ajaxUrl = serverName + "/Ajax.aspx"; // change this to whatever you call it 
    var return_value = $.ajax({
        type: "GET",
        url: ajaxUrl,
        async: false,
        data: "aop=TrailersSearch&search=" + encodeURIComponent(inputString),
        error: function(xhr, ajaxOptions, thrownError) {
            //alert(xhr.responseText);
        }
    }).responseText;

    return return_value;
}

function carousel_callback(carousel, state) {
    // BWA-HA...I have the carousel now....FEEL THE POWER!
    hpCarousel = carousel;
}

/**
* textExtract
* - returns text to sort by
*/
var textExtract = function(node) {
    // extract data from markup and return it      
    return $(node).text();
}

/**
* movieListCarousel
* - configuration for movieList carousel
* - pass in the wss code 
*/
function movieListCarousel(wssCode) {	
	$(".jcarousel-next, .jcarousel-prev").die("click");
    $('#movieListCarousel').jcarousel({
        // Configuration goes here        
        initCallback: carousel_callback,
        scroll: 4,
        animation: "fast",
        easing: "easeInOutCubic"
    });
    $(".jcarousel-next, .jcarousel-prev").live("click",function() { ReportToWss(wssCode); return true;});
}

/**
* lookup
* - handles autosuggest input, the script does not fire until at least 3 characters are typed
*/
function lookup(inputString, serverName) {
    // only allow alphanumeric and spaces
    if (inputString.match(/[^a-zA-Z0-9\-\+\&\.\,\:\!\?\' ]/g)) {
        inputString = inputString.replace(/[^a-zA-Z0-9\-\+\&\.\,\:\!\?\' ]/g, '');
    }

    if (inputString.length < 3) {
        $("#searchForm .ajaxLoad").hide();
        $('#suggestions').fadeOut().css("visibility", "hidden"); // Hide the suggestions box        
    } else if (inputString.length > 2) {
        $("#searchForm .ajaxLoad").show();

        var ajaxUrl = serverName + "/ajaxlookahead.aspx?aop=KeyAhead&search=" + encodeURIComponent(inputString);

        $.get(ajaxUrl, function(data) {
            $('#suggestions').fadeIn().css("visibility", "visible"); // Show the suggestions box
            $('#suggestions').html(data); // Fill the suggestions box
            $("#searchForm .ajaxLoad").hide(); // hide indicator
        });
    }
}

/**
* featureItemHover
* - handles feature item rollover states
*/
function featureItemHover() {
    $(".featureItem").hoverIntent(function() {
        $(this).siblings().fadeTo(50, 0.5);
    }, function() {
        $(this).siblings().fadeTo(100, 1);
    });
}

/**
* enableLocationBox
* - handles the movie times search layer pop-up behavior
*/
function enableLocationBox() {
    var hideDelay = 5000;
    var hideDelayTimer = null;
    var beingShown = false;
    var clb = $("#changeLocationBox");

    clb.hover(function() {
        if (hideDelayTimer) clearTimeout(hideDelayTimer);

        if (beingShown) {
            return; // don't trigger the pop-up again
        } else {
            beingShown = true;
        }
    }, function() {
        hideDelayTimer = setTimeout(function() {
            hideDelayTimer = null;
            clb.fadeOut("fast", function() {
                beingShown = false;
            });
        }, hideDelay);
    });
}

/**
* enableLayerBox
* - generic layer box 
* - input: selector for trigger, name of layer, left offset, top offset;
*/
function enableLayerBox(triggerSelector, targetLayer, leftOffset, topOffset) {
    var hideDelay = 400;
    var hideDelayTimer = null;
    var beingShown = false;
    var shown = false;
    var theLayer = $(targetLayer);

    var layerContent = '';
    var hoveredContent = ' ';

    $(theLayer).appendTo("body"); // only needed if rendered within the page		
    $(triggerSelector + ", " + targetLayer).hoverIntent(function(e) {

        // determine what is hovered 							
        if ($(this).attr("id") == (targetLayer)) { // if the hovered item is the layer						
            if (hideDelayTimer) clearTimeout(hideDelayTimer); // clear timer if present
            beingShown = false;
            shown = true;
        } else if ($(this).attr("class") == triggerSelector.replace(".", "")) { //if the hovered item is the trigger check to see if same one.	
            if (hoveredContent != layerContent) { // if the trigger content does not equal the layer's content	
                beingShown = false;
                shown = false;
            } else if (theLayer.css("display") == "none") { // if the titles match but the pop-up is not displayed 																												
                shown = false;
                beingShown = false;
            }
        }

        hoveredContent = $(this).children("textarea").text(); // get current hovered content 						
        layerContent = theLayer.children(".layerBoxContent").html(); // get current layer content										

        if (hideDelayTimer) clearTimeout(hideDelayTimer); // clear timer if present		

        if (shown || beingShown) {
            return; // don't trigger the pop-up again
        } else {
            beingShown = true;

            $(targetLayer + " .layerBoxContent").html($(this).children("textarea").text()); // function to populate the data in the pop-up			 			  

            theLayer.css("left", "-9999em").show();  // temporarily show the item to get the height  	    	
            var theLayerHeight = theLayer.children(".layerBoxContent").height(); //get height
            var theLayerWidth = theLayer.children(".layerBoxContent").width();
            var triggerWidth = parseInt($(triggerSelector).width());
            var locOffset = $(this).offset();

            theLayer.hide();

            theLayer.css("left", locOffset.left + triggerWidth / 2 - (theLayerWidth / 2) - leftOffset).css("top", locOffset.top - theLayerHeight - topOffset);
            beingShown = false;

            if ($.browser.msie) { // since ie doesn't support opacity animation  	    		
                theLayer.show(0, function() {
                    beingShown = false;
                    shown = true;
                });
            } else {
                theLayer.fadeIn("fast", function() {
                    beingShown = false;
                    shown = true;
                });
            }

        }
    }, function() {
        if (hideDelayTimer) clearTimeout(hideDelayTimer);

        hideDelayTimer = setTimeout(function() {
            hideDelayTimer = null;
            theLayer.hide(0, function() { shown = false; });
        }, hideDelay);
        return false;
    });
}



/**
* getScriptURL
* - used to determine the base script path. uses global.js as the base 
*/
function getScriptURL() {
    var u = parseUri($("script[src$='global.js']").attr("src"));
    var v = u.protocol + '://' + u.host + ":" + u.port + u.directory;
    return v;
}

/**
* addBrowserClass
* - dynamically inject browser type into body tag for css specificity 
* - maybe implemented on the server side eventually 
*/
function addBrowserClass() {
    if ($.browser.safari) { $("body").addClass("safari"); }
    if ($.browser.msie && $.browser.version.substr(0, 3) == "6.0") { $("body").addClass("msie6"); }
    if ($.browser.msie && $.browser.version.substr(0, 3) == "7.0") { $("body").addClass("msie7"); }
    if ($.browser.msie && $.browser.version.substr(0, 3) == "8.0") { $("body").addClass("msie8"); }
    if ($.browser.mozilla && $.browser.version.substr(0, 3) == "1.8") { $("body").addClass("ff2"); }
    if ($.browser.mozilla && $.browser.version.substr(0, 5) == "1.9.0") { $("body").addClass("ff3"); }
    if ($.browser.mozilla && $.browser.version.substr(0, 5) == "1.9.1") { $("body").addClass("ff35"); }
    if ($.browser.opera) { $("body").addClass("opera"); }
}

/** 
* browserDiagnostics
* - list out the browser details on the page for diagnostics 
*/
function browserDiagnostics() {
    jQuery.each(jQuery.browser, function(i, val) { $("<div>" + i + " : <span>" + val + "</span>").appendTo(document.body); });
}

/**
* segmentSubControl
* - controls link/content pairs within a segment
* - (WIP) somewhat specific now. look at making more generic if possible.
*/
function segmentSubControl(trigger, targetContainer, parentContainer) {
    $(trigger).click(function() {
        var getAllChildren = $(this).parent().children("a");
        var relatedLists = $(this).parents(parentContainer).children(targetContainer);
        var index = $(getAllChildren).index(this);

        if ($(this).hasClass("selected") == true) {
            // do nothing
        } else {
            $(getAllChildren).removeClass("selected");
            $(this).addClass("selected");
            $(relatedLists).hide().eq(index).show();
        }
        return false;
    });
}

/**
* burningQuestion
* - controls for burning question
*/
// Burning Question animation
function burningQuestion() {
    $("#btn-answer").click(function() {
    	var theAnswer = $("#burningQuestion #answer p").text().replace(/[^a-z0-9]/gi,''); // only accept alphanumeric
    	    	
    	$("#burningQuestion #question li").each(function(index) {    		
    		if ($(this).text().replace(/[^a-z0-9]/gi,'') != theAnswer) {
    			$(this).addClass("loser");
    		}
    	});
    	
    	$("#burningQuestion #question li.loser").animate({
    		opacity: 0.25
    	}, 300, "easeInQuint", function() {
			$("#btn-answer").hide();
			$("#btn-new-question").fadeIn();
			$("#btn-new-question").unbind().click(function() {				
		   		getNewBurningQuestion($(this).attr("data-ajax-href"));
		   		return false;
	   		});
		});
        return false;
    });
}

/**
* burningQuestion ajax goodness
* - grabs the data-ajax-url and gets the markup
*/
function getNewBurningQuestion(thisUrl) {
    $.ajax({
        url: thisUrl,
        cache: false,
        success: function (data) {
            $("#burningQuestion").html(data);
            burningQuestion();
        } 
    });
}

/**
* parseUri 1.2.2
* (c) Steven Levithan <stevenlevithan.com>
* MIT License
*/
function parseUri(str) {
    var o = parseUri.options,
		m = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
		uri = {},
		i = 14;

    while (i--) uri[o.key[i]] = m[i] || "";

    uri[o.q.name] = {};
    uri[o.key[12]].replace(o.q.parser, function($0, $1, $2) {
        if ($1) uri[o.q.name][$1] = $2;
    });

    return uri;
};

parseUri.options = {
    strictMode: false,
    key: ["source", "protocol", "authority", "userInfo", "user", "password", "host", "port", "relative", "path", "directory", "file", "query", "anchor"],
    q: {
        name: "queryKey",
        parser: /(?:^|&)([^&=]*)=?([^&]*)/g
    },
    parser: {
        strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
        loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
    }
};

/**
* Modal Pop-up Functions
*/
// Popup code
var gPopupMask = null;
var gPopupContainer = null;
var gPopFrame = null;
var gReturnFunc;
var gPopupIsShown = false;
var gDefaultPage = "";
var gHideSelects = false;
var gReturnVal = null;

var gTabIndexes = new Array();
// Pre-defined list of tags we want to disable/enable tabbing into
var gTabbableTags = new Array("A", "BUTTON", "TEXTAREA", "INPUT", "IFRAME");

// If using Mozilla or Firefox, use Tab-key trap.
if (!document.all) {
    document.onkeypress = keyDownHandler;
}

/**
* initPopup
* Initializes popup code on load.	
*/
function initPopUp() {
    // Add the HTML to the body
    theBody = document.getElementsByTagName('BODY')[0];
    popmask = document.createElement('div');
    popmask.id = 'popupMask';
    popcont = document.createElement('div');
    popcont.id = 'popupContainer';
    popcont.innerHTML = '' +
		'<div id="popupInner">' +
			'<div id="popupTitleBar">' +
				'<div id="popupTitle"></div>' +
				'<div id="popupControls">' +

				'</div>' +
			'</div>' +
			'<iframe src="' + gDefaultPage + '" style="width:100%;height:100%;background-color:transparent;" scrolling="auto" frameborder="0" allowtransparency="true" id="popupFrame" name="popupFrame" width="100%" height="100%"></iframe>' +
		'</div>';
    theBody.appendChild(popmask);
    theBody.appendChild(popcont);

    gPopupMask = document.getElementById("popupMask");
    gPopupContainer = document.getElementById("popupContainer");
    gPopFrame = document.getElementById("popupFrame");

    // check to see if this is IE version 6 or lower. hide select boxes if so
    // maybe they'll fix this in version 7?
    var brsVersion = parseInt(window.navigator.appVersion.charAt(0), 10);
    if (brsVersion <= 6 && window.navigator.userAgent.indexOf("MSIE") > -1) {
        gHideSelects = true;
    }

    // Add onclick handlers to 'a' elements of class submodal or submodal-width-height	
    $("a.submodal, a.submodal-width-height").click(function() {
        var width = 400;
        var height = 200;
        // Parse out optional width and height from className
        params = this.className.split('-');
        if (params.length == 3) {
            width = parseInt(params[1]);
            height = parseInt(params[2]);
        }
        showPopWin(this.href, width, height, null); return false;
    });
}

/**
* showPopWin
* @argument width - int in pixels
* @argument height - int in pixels
* @argument url - url to display
* @argument returnFunc - function to call when returning true from the window.
* @argument showCloseBox - show the close box - default true
*/
function showPopWin(url, width, height, returnFunc, showCloseBox) {
    // show or hide the window close widget
    if (showCloseBox == null || showCloseBox == true) {
        document.getElementById("popCloseBox").style.display = "none";
    } else {
        document.getElementById("popCloseBox").style.display = "none";
    }
    gPopupIsShown = true;
    disableTabIndexes();
    gPopupMask.style.display = "block";
    gPopupContainer.style.display = "block";
    // calculate where to place the window on screen
    centerPopWin(width, height);

    var titleBarHeight = parseInt(document.getElementById("popupTitleBar").offsetHeight, 10);


    gPopupContainer.style.width = width + "px";
    gPopupContainer.style.height = (height + titleBarHeight + 2) + "px";

    setMaskSize();

    // need to set the width of the iframe to the title bar width because of the dropshadow
    // some oddness was occuring and causing the frame to poke outside the border in IE6
    gPopFrame.style.width = parseInt(document.getElementById("popupTitleBar").offsetWidth, 10) + "px";
    gPopFrame.style.height = (height) + "px";

    // set the url
    gPopFrame.src = url;

    gReturnFunc = returnFunc;
    // for IE
    if (gHideSelects == true) {
        hideSelectBoxes();
    }

    window.setTimeout("setPopTitle();", 600);
}

var gi = 0;

/**
* centerPopWin
* @argument width - int in pixels
* @argument height - int in pixels
* - add description
*/
function centerPopWin(width, height) {
    if (gPopupIsShown == true) {
        if (width == null || isNaN(width)) {
            width = gPopupContainer.offsetWidth;
        }
        if (height == null) {
            height = gPopupContainer.offsetHeight;
        }

        //var theBody = document.documentElement;
        var theBody = document.getElementsByTagName("BODY")[0];
        //theBody.style.overflow = "hidden";
        var scTop = parseInt($(document).scrollTop(), 10);
        var scLeft = parseInt(theBody.scrollLeft, 10);

        setMaskSize();

        //window.status = gPopupMask.style.top + " " + gPopupMask.style.left + " " + gi++;

        var titleBarHeight = parseInt(document.getElementById("popupTitleBar").offsetHeight, 10);

        var fullHeight = $(window).height(); //getViewportHeight();
        var fullWidth = $(window).width(); //getViewportWidth();

        gPopupContainer.style.top = (scTop + ((fullHeight - (height + titleBarHeight)) / 2)) + "px";
        gPopupContainer.style.left = (scLeft + ((fullWidth - width) / 2)) + "px";
        //alert(fullWidth + " " + width + " " + gPopupContainer.style.left);
    }
}

$(window).resize(centerPopWin);
$(window).scroll(centerPopWin);

/**
* setMastSize
* - sets the size of the popup mask. 
*/
function setMaskSize() {
    var theBody = document.getElementsByTagName("BODY")[0];

    var fullHeight = $(window).height(); // getViewportHeight();
    var fullWidth = $(window).width(); //getViewportWidth();

    // Determine what's bigger, scrollHeight or fullHeight / width
    if (fullHeight > theBody.scrollHeight) {
        popHeight = fullHeight;
    } else {
        popHeight = theBody.scrollHeight;
    }

    if (fullWidth > theBody.scrollWidth) {
        popWidth = fullWidth;
    } else {
        popWidth = theBody.scrollWidth;
    }

    gPopupMask.style.height = popHeight + "px";
    gPopupMask.style.width = popWidth + "px";
}

/**
* hidePopWin	
* @argument callReturnFunc - bool - determines if we call the return function specified
* @argument returnVal - anything - return value 
*/
function hidePopWin(callReturnFunc) {
    gPopupIsShown = false;
    var theBody = document.getElementsByTagName("BODY")[0];
    theBody.style.overflow = "";
    restoreTabIndexes();
    if (gPopupMask == null) {
        return;
    }
    gPopupMask.style.display = "none";
    gPopupContainer.style.display = "none";
    if (callReturnFunc == true && gReturnFunc != null) {
        // Set the return code to run in a timeout.
        // Was having issues using with an Ajax.Request();
        gReturnVal = window.frames["popupFrame"].returnVal;
        window.setTimeout('gReturnFunc(gReturnVal);', 1);
    }
    gPopFrame.src = gDefaultPage;
    // display all select boxes
    if (gHideSelects == true) {
        displaySelectBoxes();
    }
}

/**
* setPopTitle
* Sets the popup title based on the title of the html document it contains.
* Uses a timeout to keep checking until the title is valid.
*/
function setPopTitle() {
    return;
    if (window.frames["popupFrame"].document.title == null) {
        window.setTimeout("setPopTitle();", 10);
    } else {
        document.getElementById("popupTitle").innerHTML = window.frames["popupFrame"].document.title;
    }
}

/**
* keyDownHandler
* Tab key trap. iff popup is shown and key was [TAB], suppress it.
* @argument e - event - keyboard event that caused this function to be called.
*/
function keyDownHandler(e) {
    if (gPopupIsShown && e.keyCode == 9) return false;
}

/**
* disableTabIndexes
* - For IE.  Go through predefined tags and disable tabbing into them.
*/
function disableTabIndexes() {
    if (document.all) {
        var i = 0;
        for (var j = 0; j < gTabbableTags.length; j++) {
            var tagElements = document.getElementsByTagName(gTabbableTags[j]);
            for (var k = 0; k < tagElements.length; k++) {
                gTabIndexes[i] = tagElements[k].tabIndex;
                tagElements[k].tabIndex = "-1";
                i++;
            }
        }
    }
}

/**
* restoreTabIndexes
* - For IE. Restore tab-indexes.
*/
function restoreTabIndexes() {
    if (document.all) {
        var i = 0;
        for (var j = 0; j < gTabbableTags.length; j++) {
            var tagElements = document.getElementsByTagName(gTabbableTags[j]);
            for (var k = 0; k < tagElements.length; k++) {
                tagElements[k].tabIndex = gTabIndexes[i];
                tagElements[k].tabEnabled = true;
                i++;
            }
        }
    }
}

/**
* hideSelectBoxes
* - Hides all drop down form select boxes on the screen so they do not appear above the mask layer.
* - IE has a problem with wanted select form tags to always be the topmost z-index or layer
*
* Thanks for the code Scott!
*/
function hideSelectBoxes() {
    for (var i = 0; i < document.forms.length; i++) {
        for (var e = 0; e < document.forms[i].length; e++) {
            if (document.forms[i].elements[e].tagName == "SELECT") {
                document.forms[i].elements[e].style.visibility = "hidden";
            }
        }
    }
}

/**
* displaySelectBoxes
* Makes all drop down form select boxes on the screen visible so they do not reappear after the dialog is closed.
* IE has a problem with wanted select form tags to always be the topmost z-index or layer
*/
function displaySelectBoxes() {
    for (var i = 0; i < document.forms.length; i++) {
        for (var e = 0; e < document.forms[i].length; e++) {
            if (document.forms[i].elements[e].tagName == "SELECT") {
                document.forms[i].elements[e].style.visibility = "visible";
            }
        }
    }
}

// Locates the random ad unit number, i.e. "ord=" param value, from the given ad markup and replaces 
// it with the given alternate random number.
//
function ReplaceAdRandomNumber(adMarkup, altRandNum) {
    if (adMarkup == null || altRandNum == null) {
        return adMarkup;
    }

    // Use RegEx to find and replace the random number param.
    var regExPattern = /(ord=)[^"'\?;]+(["'\?;])/gi;

    return adMarkup.replace(regExPattern, "$1" + altRandNum + "$2");
}

// Generate a random number used to replace the one in the ad
// to ensure that we will have a new ad.
function GenerateRandomNumber() {
    var rnd = "0";
    var today = new Date();
    rnd += today.getHours();
    rnd += "0";
    rnd += today.getMinutes();
    rnd += today.getSeconds();
    rnd += rnd;

    return rnd;
}

// Refresh all of the ads on the page.
function RefreshAds() {
    var divContentArray = [];
    var divIdArray = [];

    // Iterate through the elements that carry this class so we can
    // grab the current values of them and
    $(".AdUnit").each(function(i) {
        // Grab the content so we can manipulate it.
        //
        // First try grabbing from the original markup written to the container.
        var divContent = $(this).html();
        divContent = ReplaceAdRandomNumber(divContent, GenerateRandomNumber());

        this.innerHTML = divContent;
    });
}

//This function is used to handle enter key event on the pages.
function clickButton(e, buttonid) {
    var bt = document.getElementById(buttonid);
    if (typeof bt == 'object') {
        if (navigator.appName.indexOf("Netscape") > (-1)) {
            if (e.keyCode == 13) {
                e.returnValue = false;
                e.cancel = true;
                bt.click();
                return false;
            }
        }
        if (navigator.appName.indexOf("Microsoft Internet Explorer") > (-1)) {
            if (event.keyCode == 13) {
                event.returnValue = false;
                event.cancel = true;
                bt.click();
                return false;
            }
        }
    }
}

// Parses out the WSS LID and LPOS from the given elem param and calls the WSS _hbLink function.
// This function parses the LID and LPOS from a WSS link name of the form "&lid=[LID]&lpos=[LPOS]"
// Param elem can be either a DOM element or a string. If a DOM element, the name attribute is 
// used as the WSS link name.
function ReportToWss(elem) {
    if (elem != null) {
        var linkName = (elem + "");

        // Not a string so assume it's a DOM element.
        if (typeof (elem) != "string") {
            linkName = $(elem).attr("name");
        }

        // Parse the link name into an associative array.
        var nameValueArray = ToNameValueArray(linkName);
        if (nameValueArray != null) {
            var lid = nameValueArray["lid"];
            var lpos = nameValueArray["lpos"];

            if (lid != null && lid.length > 0) {
                if (lpos == null || lpos.length <= 0) {
                    lpos = lid;
                }

                try {
                    //alert("Calling _hbLink('" + lid + "', '" + lpos + "');");
                    _hbLink(lid, lpos);
                }
                catch (e) {
                    alert("WSS error:\n" + e);
                }
            }
        }
    }
}

// This Function replicates the Classic ReportToWss function's behavior
// But it make is so that the link is tracked under a specified Content Group
function ReportToWssWithContentGroup(elem, group) {
    if (elem != null) {
        var linkName = (elem + "");
		var groupName = (group + "");
		// Save the current Content Group
		var current =  hbx.mlc;
		
        // Not a string so assume it's a DOM element.
        if (typeof (elem) != "string") {
            linkName = $(elem).attr("name");
        }
		
		// Group not a String, don't set the group, and the default one will be used
		if ((typeof (group) == "string") && (groupName.length > 0)) {
			try {
				// Update the Content Group
				_hbSet('vcon', groupName);
			}	
			catch (e) {
				alert("WSS error:\n" + e);
			}
        }
		
        // Parse the link name into an associative array.
        var nameValueArray = ToNameValueArray(linkName);
        if (nameValueArray != null) {
            var lid = nameValueArray["lid"];
            var lpos = nameValueArray["lpos"];

            if (lid != null && lid.length > 0) {
                if (lpos == null || lpos.length <= 0) {
                    lpos = lid;
                }

                try {
                    //alert("Calling _hbLink('" + lid + "', '" + lpos + "');");
                    _hbLink(lid, lpos);
					// Restore the Content Group to its previous value
					_hbSet('vcon', current);
					_hbSend();
                }
                catch (e) {
                    alert("WSS error:\n" + e);
                }
            }
        }		
    }
}

// Converts the given urlCommandStr to an associative array.
function ToNameValueArray(urlCommandStr) {
    var nameValueArray = new Array();
    if (urlCommandStr != null && typeof (urlCommandStr) == "string") {
        var ampersandSplit = urlCommandStr.split("&");
        if (ampersandSplit != null && ampersandSplit.length > 0) {
            for (var i = 0; i < ampersandSplit.length; i++) {
                var equalsSplit = ampersandSplit[i].split("=");

                if (equalsSplit != null && equalsSplit.length > 1) {
                    nameValueArray[equalsSplit[0]] = equalsSplit[1];
                }
            }
        }
    }
    return nameValueArray;
}

//Popup window
function popWin(url, windowName) {
    var w = 990;
    var h = 560;

    var centerW = (window.screen.width - w) / 2;
    var centerH = (window.screen.height - h) / 2;

    if (windowName == null) {
        windowName = 'Movies';
    }

    var newWindow = window.open(url, windowName, 'resizable=yes,scrollbars=yes,width=' + w + ',height=' + h + ',left=' + centerW + ',top=' + centerH);


    if (newWindow != null) {

        newWindow.focus();
    }
}

/**
* enablePhotoViewer
* theTarget = the CSS selector of the structure to enable serial scroll
*/
function enablePhotoViewer(theTarget) {	
	$(theTarget).serialScroll({
		items:'li',
		prev:'#photoViewControls .prev',
		next:'#photoViewControls .next',
		offset:0, //when scrolling to photo, stop 230 before reaching it (from the left)
		start:0, //as we are centering it, start at the 2nd
		duration:650,
		force:true,
		stop:true,
		lock:false,
		cycle:false, //don't pull back once you reach the end
		easing:'easeInOutQuart', //use this easing equation for a funny effect
		jump: true, //click on the images to scroll to them
		onBefore:function(e, elem, $pane, $items, pos){
			var countPad;
		    if (pos >= 0) {		
		    	updateControls(pos);
		    	
		    	$(elem).prev().animate({opacity:.15},250); // fade down
		    	$(elem).next().animate({opacity:.15},250); // fade down
		    	$("#photoCaption").html($(elem).find("img").siblings("span").html()); // update caption
		    	if ($("#container").hasClass("guides")) {
		    		if (pos < 9) { countPad = "0" + (pos+1); } else { countPad = pos+1; } // modify counter string for leading zero
		    		$("#photoCount strong").text(countPad); // update counter
	    		} else {
	    			countPad = pos+1; 
		    		$("#photoCount em").text(countPad); // update counter	
	    		}		    	
		    }	  
		},
		onAfter:function(elem){
			$(elem).animate({ opacity: 1 },200,"easeOutQuart");
			$("#photoCaption").html($(elem).find("img").siblings("span").html());			
			// we should add WSS stuff here if possible to keep it clean				
			_hbPageView(hbx.pn, hbx.mlc);
			RefreshAds();
		}			
	});	
	
	function updateControls(position) {
		var lastItem = ($(theTarget + " li").length)-1;
		$('#photoViewControls button').removeClass("disable");
		if (position == 0) {
    		$('#photoViewControls .prev').addClass("disable");
    	} 
    	if (position == lastItem ) {
    		$('#photoViewControls .next').addClass("disable");
    	}	
	}
	
	// add keyboard controls
	$(document).keydown(function(e) {
        switch (e.which) {
            case 37:
                $(theTarget).trigger("prev");
                break;
            case 39:
                $(theTarget).trigger("next");
                break;
            default:
            // code to be executed if event is different from case 37 and 39
        }
    });		
    
    // add touch abilities
    $(theTarget).touchwipe({
		wipeLeft: function() { $(theTarget).trigger("next"); },
		wipeRight: function() { $(theTarget).trigger("prev"); },
		preventDefaultEvents: true
	});	
	
	updateControls(0);
}

/**
* enableMoviePopup
* - no parameters
*/
function enableMoviePopup(theSelector) {
	var config = {    
		over: hoverOver, // function = onMouseOver callback (REQUIRED)    
		timeout: 500, // number = milliseconds delay before onMouseOut  
		interval: 400, // interval on when it should pop-up
		out: hoverOut // function = onMouseOut callback (REQUIRED)    
	};
	var showMoviePopup = false;
	
	// populate the box
	function populateMoviePopup(thisEl) {
		$("#movieInfoContainer").html($(thisEl).find("textarea").text()).show().css("visibility","hidden");
	}
	
	// position the box
	function positionMoviePopup(thisEl) {	
		var offSetX = 11;
		var offSetY = 11;
		if ($.browser.msie && (parseInt($.browser.version.substr(0, 3)) < 9)) { offSetX = 14; offSetY = 14; }
		offSetY = offSetY + $("#movieInfoContainer").find("#addedInfo").outerHeight();
				
		var posX = parseFloat($(thisEl).offset().left)-offSetX;
		var posY = parseFloat($(thisEl).offset().top)-offSetY;

		$("#movieInfoContainer").css("left",posX).css("top",posY);
		// positionCheck("#movieInfoContainer");
		$("#movieInfoContainer").css("visibility","visible").hide().fadeIn(300);	
	}
	
	function moveSuccess() {
		return true;
	}
	
	function positionCheck(element) {
		elPos = $(element).position();
		elHeight = $(element).height();
		totalHeight = $(document).scrollTop() + $(window).height();		
			
		if (elPos.top < $(document).scrollTop()) {
			$(document).scrollTo(elPos.top-10,"slow",{easing:"easeOutQuint"});
		} else if ((elPos.top + elHeight) > totalHeight) {
			theDiff = $(document).scrollTop() + ((elPos.top + elHeight) - totalHeight)
			$(document).scrollTo(theDiff+10,"slow",{easing:"easeOutQuint"});
		} 
	}
	
	function hoverOver() {
		$("#movieInfoContainer").remove();
		$("body").append("<div id='movieInfoContainer'><div id='movieInfo'></div><div id='movieActions'></div></div>");	
		populateMoviePopup(this);
		positionMoviePopup(this);
		moviePopupMouseOver();
	}
	
	/* apply hover actions to dynamic layer */
    function moviePopupMouseOver() {
        $("#movieInfoContainer").hover(function () {
            showMoviePopup = true;

            /* Omniture onhover tracking for movie popup */
            $.getScript(scriptPath + sCode, function () {
                if (s.c_r('hovercc') > 0) {
                    s.c_w('hovercc', parseInt(s.c_r('hovercc')) + Number(1), 0)
                }
                else {
                    s.c_w('hovercc', 1, 0);
                }
            });

        }, function () {
            $("#movieInfoContainer").fadeOut(200, function () { $(this).remove() });
            showMoviePopup = false;
        });
    }
	
	function hoverOut() { /* do nothing at this time*/ }
	
	// setup the trigger
	$(theSelector).hoverIntent(config);
}

/*
 * function createTableList 
 * breaks up a ol/ul into multiple columns sorted in the order of the list
 */
function createTableList(thisEl, columns) {    
	// clone the original list                    		                		
	var ogList = $(thisEl).find("li").clone();
	// calculate the number of rows
	var tableRows = Math.ceil(ogList.length/columns);
	var tableColumns = columns;
	
	// create table
	var tableList = $("<div id='menuTable'><table></table></div>");                    			
	$(tableList).find("table").append("<tbody><tr></tr></tbody>");
	
	// for the number of columns
	for (i=0; i<tableColumns;i++) {
		//create a table cell then add each list item
		$(tableList).find("tr").append("<td style='width:"+100/columns+"%;'><ul></ul></td>");
		var limitStart = i*tableRows;                    			
		var limitEnd = i*tableRows+tableRows;
		var partialList = $(ogList).slice(limitStart, limitEnd);                    			
		$(tableList).find("td ul").last().html(partialList);							    
	}                    		
	// append table                    		
	$(thisEl).append(tableList);                    		
}

function removeTableList() {
	$("#menuTable").remove();
}

/*
 * function checkScrollingForDisqus 
 * dynamically add disqus to page only if it's in the viewport
 */
function checkScrollingForDisqus(event) { 
    $('#disqus_thread:in-viewport').each(function() { 
    	(function () {
	        var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
	        dsq.src = 'http://' + disqus_shortname + '.disqus.com/embed.js';
	        (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
	    })();
    	$(window).unbind('scroll', checkScrollingForDisqus);
	});
}

/* Omniture Tracking for Watch It actions in At Home and In Theater pages */
function ReportToOmnitureWatchItClicks(elem, movieName, linkType, watchItType) {
    $.getScript(scriptPath + sCode, function () {
        s.linkTrackVars = 'prop43,eVar43,eVar45,prop45,events';
        s.linkTrackEvents = 'event43,event44';
        s.events = 'event43,event44';
        s.prop43 = movieName;
        s.eVar43 = 'D=c43';
        s.prop45 = watchItType;
        s.eVar45 = 'D=c45';

        s.tl(elem, linkType, watchItType);
    });
}

/* Omniture Tracking for Watch It actions in Movie page */
function ReportToOmnitureMovieWatchItClicks(elem, movieName, linkType, watchItType) {
    $.getScript(scriptPath + sCode, function () {
        s.linkTrackVars = 'prop43,eVar43,eVar45,prop45,events';
        s.linkTrackEvents = 'event42,event44';
        s.events = 'event42,event44';
        s.prop43 = movieName;
        s.eVar43 = 'D=c43';
        s.prop45 = watchItType;
        s.eVar45 = 'D=c45';

        s.tl(elem, linkType, watchItType);
    });
}

/* Omniture Tracking for Fandango Click-Through from Movie Times Page  */
$(".movieTimesContainer .theaterList .movieListings .showtimesWrapper .showtimes li a, .movieTimesContainer .theaterList .movieListings .tickets a").click(function (e) {
    var movieName = $(this).attr("omniture-moviename");
    var clickThruValue = $(this).attr("omniture-clickthru-value");
    var elem = this;
    $.getScript(scriptPath + sCode, function () {
        if (movieName != "" && (typeof (movieName) != "undefined") && clickThruValue != "" && (typeof (clickThruValue) != "undefined")) {
            s.linkTrackVars = 'prop43,eVar43,eVar42,events';
            s.linkTrackEvents = 'event50';
            s.events = 'event50';
            s.prop43 = movieName;
            s.eVar43 = 'D=c43';
            s.evar42 = clickThruValue;

            s.tl(elem, 'e', 'buy tickets');
        }
    });
});

/* Omniture Tracking for RSS Service (google, yahoo, msn) clicks */
function ReportToOmnitureRssServiceClicks(elem, rssService) {
    $.getScript(scriptPath + sCode, function () {
        s.linkTrackVars = 'prop30,eVar30,events';
        s.linkTrackEvents = 'event36';
        s.events = 'event36';
        s.prop30 = 'RSS| All Features | ' + rssService;
        s.eVar30 = 'D=c30';

        s.tl(elem, 'e', 'RSS Subscription');
    });
}























