/* script versions to use */
var jQsimpleModal = "jquery.simplemodal.pack.js";
var jQhint        = "jquery.hint.pack.js";
var jQeasing      = "jquery.easing.pack.js";
var jQhoverIntent = "jquery.hoverIntent.js";
var jQCarousel    = "jquery.jcarousel.pack.js";
var jQlivequery   = "livequery.js";
var siteScripts   = "scripts.js";
var sitePrintable = "printable.js";
var siteLogonPopup= "logonpopup.js";
var siteFAJAX     = "fandangoajax.js";
var siteQuickRate = "quickRate.js";

// activate the drop-down
$(document).ready(function() {
	/* set scriptPath */
    scriptPath = getScriptURL();
    
    /* add specificity */
    addBrowserClass();
	
	/* lazy script loading */
	$.ajaxSetup({ cache: true }); // make sure loading from cache
	$.getScript(scriptPath + jQeasing); // pre-load easing
	$.getScript(scriptPath + jQhoverIntent); // pre-load hoverIntent
	$.getScript(scriptPath + siteScripts); // pre-load hoverIntent
	$.getScript(scriptPath + sitePrintable); // pre-load hoverIntent
	
	activateMovieJump();	
	
	$("a.fblogout").click(function(e) {
		FB.ensureInit(function() {
			FB.Connect.get_status().waitUntilReady(function(status) {
				if (status == FB.ConnectState.connected) {
					e.preventDefault();
					FB.Connect.logoutAndRedirect($("a.fblogout").attr("href"));
				}
			});
		});
	});
	
	if (window.FB) {
		FB.ensureInit(function() {
			$("fb\\:name, name").click(function() {
				$(this).find("a.FB_Link").attr("target", "_blank");
			});
		})
	}
});

// search drop down functionality
function activateMovieJump() {	
	var offsetH = parseInt($("#drop_down_shadow .topwrap").css("height"));
	
	$("ul#cmd div.activate").hover(function() {			
		$("#expand").css("top","-1px").css("left","-1px");
		if (window.RefreshPulldownAd) { RefreshPulldownAd(); }
		$("#drop_down_shim")
				.css("width",$("#expand").outerWidth()-22)
				.css("height",$("#expand").outerHeight()-offsetH-5)
				.show();				
		$(".topwrap").css("width", $("#expand").outerWidth()+22); //-16
		$(".bottomwrap").css("width", $("#expand").outerWidth()+22);
		$(".leftwrap").css("height",$("#expand").outerHeight()-offsetH-5); //-16
		
		//ie6 condition
		if ($.browser.msie && (typeof XMLHttpRequest == 'function' || !window.XMLHttpRequest)) { 
			$(".rightwrap") 
				.css("height",$("#expand").outerHeight()-offsetH)  
				.css("width" ,$("#expand").outerWidth()+6);
			var iHeight = $("#movieDropDownContents").outerHeight()-offsetH;
			var iWidth = $("#movieDropDownContents").outerWidth();
			var dropdownFrame = "<IFRAME id='dropdown-cover' style='height:"+iHeight+"px; width:"+iWidth+"px; position: absolute;' src='javascript:false;' frameBorder='0' scrolling='no'></IFRAME>";
			$(dropdownFrame).insertBefore("#movieDropDownContents");	
		} else {
			$(".rightwrap") 
			.css("height",$("#expand").outerHeight()-offsetH-5)  
			.css("width" ,$("#expand").outerWidth());
		}
		$("#locationDropDown").removeClass("open");
		$("#location_search_field input.input_search").blur();
		
		$("#drop_down_shadow").show();				
		
	},function() {
		$("#drop_down_shadow").hide();
		if ($("#dropdown-cover")) { $("#dropdown-cover").remove(); } // ie6 iframe removal
		$("#expand").css("top","-9999px").css("left","-9999px");
	});
	
	// moving over empty area 
	$("#movieDropDownEmpty").mouseover(function() {
		$("#drop_down_shadow").hide();
		if ($("#dropdown-cover")) { $("#dropdown-cover").remove(); } // ie6 iframe removal
		$("#expand").css("top","-9999px").css("left","-9999px");
	});
	
	// location drop down	
	if ($("#location_search input.input_search").size() > 0) {
		var hOffset = $("#header").offset(); 
		var locPos = $("#location_search").offset(); 
		
		$("#locationDropDown").css("top",locPos.top-hOffset.top+44).css("left",locPos.left-hOffset.left);
		$("#location_search input.input_search").focus(function() {
			// check if populated		
			if ($("#locationDropDownContents").children().size() > 0) {		
		        $("#locationDropDown").toggleClass("open");             
		        $("#locationDropDown").hover(function() {
		            $(this).show();
		        }, function() {
		            $(this).removeClass("open");
		        });
		        
		        $("#locationDropDownContents a").click(function() {
			        $("#location_search input.input_search").attr("value", $(this).html());
		    	    $("#locationDropDown").removeClass("open");
		    	});                   	    	
	    	}
		});         
	}
}

function positionGenericPopup() {
	if ($(".generic_dialog").size() > 0) {
		var parentTag = $(".generic_dialog").parent().get(0).tagName.toLowerCase();
		if (parentTag != "form") {
			$(".generic_dialog").appendTo("form:first");
		}
	
		var scrollTop = $(window).scrollTop();
		$(".generic_dialog").css("top", scrollTop+200);
		$(".generic_dialog").show();
	}	
}

function closeGenericPopup(thisEl) {
	if ($.browser.msie) {
		$(thisEl).hide(); // can add .empty() to destroy contents if ajax
	} else {
		$(thisEl).fadeOut(); // can add .empty() to destroy contents if ajax	
	}		
}


navList = function() {    
	if (document.all&&document.getElementById) {
		navRoot = document.getElementById("nav");
		for (i=0; navRoot != null && i<navRoot.childNodes.length; i++) {
			node = navRoot.childNodes[i];
			if (node.nodeName=="LI") {
				node.onmouseover=function() {
					this.className+=" over";
					navCover();
				}
				node.onmouseout=function() {
					this.className=this.className.replace(" over", "");
					navUnCover();
				}
			}
		}
	}
}
window.onload=navList;

// covers selects for IE 6<
function navCover() {            
	if ($.browser.msie && (typeof XMLHttpRequest == 'function' || !window.XMLHttpRequest)) { // $.browser.msie && typeof XMLHttpRequest == 'function'			
		// only run when necessary			
		if ($("li.over > ul").size() > 0) {	
		    // get location of dropdown		 			
		    var navDrop = $("li.over > ul");				    
		    navHeight = navDrop.height()+5;				    
		    
		    // fix for menu adjustment  
		    if ($(navDrop).parent().attr("id") == "nav_myfandango") {
		        var coverFrame = "<IFRAME id='nav-cover' style='height:"+navHeight+"px; left: -85px;' src='javascript:false;' frameBorder='0' scrolling='no'></IFRAME>";
		    } else {
		        var coverFrame = "<IFRAME id='nav-cover' style='height:"+navHeight+"px;' src='javascript:false;' frameBorder='0' scrolling='no'></IFRAME>";
		    }
		    
		    $(coverFrame).insertBefore(navDrop);			
		}
	}
}
function navUnCover() {
	if ($.browser.msie && (typeof XMLHttpRequest == 'function' || !window.XMLHttpRequest)) { 
		$("#nav-cover").remove();
	}
}

/* clear field value function: removes the default value onfocus, and adds back if nothing entered */
function fieldClear(obj, defaultSearchTxt) {
        if(obj.Val) {
	        if (obj.value == '') { 
		        obj.value = obj.Val;
		        obj.Val = null;
		        obj.first = null;
	        } 
	        else {
		        obj.Val = null;
	        }
        } else if (!obj.first) { 
	        obj.Val = obj.value;
	        //if defaultSearchTxt param is null or text is equal to defaultSearchText then remove default value
	        if((!defaultSearchTxt) || 
	           ((defaultSearchTxt) && (obj.value.toLowerCase() == defaultSearchTxt.toLowerCase())))
	        {
	            obj.value = ''; 
	        }
	        obj.first = 'true';
        }
}

// 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 = (GetOriginalContainerContent == null ? null : GetOriginalContainerContent(this.id));
	    // If not found then grab the current markup.
	    if (divContent == null || divContent == "")
	    {
	    	divContent = $(this).html();
	    }
	    else
	    {
	    	//alert("Found original markup. " + this.id);
	    }
	    
	    divContent = ReplaceAdRandomNumber(divContent, GenerateRandomNumber());

	    // Check to make sure that the content has actually changed...just in case
	    // we picked up an item that has the "AdUnit" class but is not really an
	    // ad unit.
	    if (divContent != $(this).html())
	    {
	    	// 2008-05-30 jmock: Some ads misbehave and write outside of their container IFRAME.
	    	// When this happens the container DIV will have more than 1 child.
	    	// We have seen problems with refreshing this type of ad so we will skip these, 
	    	// for example, FireFox spikes the CPU, becomes unresponsive, and just hangs... very bad.
	    	if ($(this).children().length <= 1)
	    	{
			divIdArray[i] = this.id;
			divContentArray[i] = divContent;

			this.innerHTML = "";
		}
	    }
	});

	// Iterate through the ids that we have and write in the new iframe content
	for (i=0;i<divContentArray.length;i++)
	{
		try
		{
			if (divIdArray[i] != null && divContentArray[i] != null)
			{
				var elem = document.getElementById(divIdArray[i]);
				if (elem != null)
				{
					elem.innerHTML = divContentArray[i];
				}
			}
	    	}
	    	catch (e)
	    	{
	    	}
	}
}

// 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;
}

// 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
				{
					_hbLink(lid, lpos);
				}
				catch (e)
				{
				    // do nothing.
				}
			}
		}
	}
}

// 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;
}
    
/* Load javascript dynamically, or when the user runs a feature that requires a script. 
   if (myfunction) {  }
   else { $import('http://www.example.com/myfile.js'); }
*/
 
function $import(src) {
  var scriptElem = document.createElement('script');
  scriptElem.setAttribute('src',src);
  scriptElem.setAttribute('type','text/javascript');
  document.getElementsByTagName('head')[0].appendChild(scriptElem);
}

// import with a random query parameter to avoid caching
function $importNoCache(src) {
  var ms = new Date().getTime().toString();
  var seed = "?" + ms; 
  $import(src + seed);
}  

/*
	parseUri 1.2.1
	(c) 2007 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*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
	}
};

/**
 * 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");}
}


/**
 * site popUps
 * - this section contains all the pop-up code used on the site.
 */
$(document).ready(function(){
	$("a").filter(".popup").click(function(){
		this.blur();
		popWin(this.href);
		return false;
	});
});

function popWin(url) {
	var w = 380;
	var h = 390;
	var centerW = (window.screen.width - w) / 2; 
	var centerH = (window.screen.height - h) / 2;
	var newWindow = window.open(url, 'Fandango', 'resizable=0,scrollbars=no,width=' + w + ',height=' + h + ',left=' + centerW + ',top=' + centerH);
	if (newWindow != null)
	{
		newWindow.focus();
	}
}

function defaultPopup(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 = 'Fandango';
	}
	
	var newWindow = window.open(url, windowName, 'resizable=yes,scrollbars=yes,width=' + w + ',height=' + h + ',left=' + centerW + ',top=' + centerH);
	if (newWindow != null)
	{
		newWindow.focus();
	}
}

function customPopup(url, windowName, width, height) {    
	var centerW = (window.screen.width - width) / 2; 
	var centerH = (window.screen.height - height) / 2;
	
	if (windowName == null)
	{
		windowName = 'Fandango';
	}
	
	var newWindow = window.open(url, windowName, 'resizable=yes,scrollbars=yes,width=' + width + ',height=' + height + ',left=' + centerW + ',top=' + centerH);
	if (newWindow != null)
	{
		newWindow.focus();
	}
}

function largePopup(url) {
    defaultPopup(url, 'PurchaseFooterPopup');
}