margin_fix = 0;

(function(window, jQuery, undefined) {
	var User = window.User = {
		'uid': null,
		'session_key': null,
		'secret': null,
		'sig': null
	};
	
	var __DC__ = window.__DC__ = {
		track: function() {
			var r = Math.pow(10, 17) * Math.random();
			$('body').append($('<img>').attr({
				'width': 1,
				'height': 1,
				'src': 'http://ad.doubleclick.net/activity;src=1343940;type=ticke174;cat=ticke005;ord=1;num=' + r + '?'
			}));
		}
	};
	
	var __FB__ = window.__FB__ = {
		session: null,
		init: function() {
			if(!window.FB_RequireFeatures)
				return;
			
			FB_RequireFeatures(['Connect'], function() {
				FB.init('40ab8747f0f2dc1e708b972bd852d2ad', 'xd_receiver.htm');
				__FB__.connect = FB.Connect;
				__FB__.api = FB.Facebook.apiClient;
				__FB__.ensurePerms();
			});
		},
		ensurePerms: function(callback) {
			__FB__.api.users_hasAppPermission('publish_stream', function(valid) {
				if(!!valid)
					jQuery('#fbContent').html('You are already signed up to receive Mamma Mia notifications on Facebook.');			
			});
		},
		ensureSession: function() {
			Logger.LOG('Ensuring session...');
			__FB__.connect.get_status().waitUntilReady(function(status) {
				switch(status) {
					case FB.ConnectState.connected:
						jQuery('#fbContent').html('You are already signed up to receive Mamma Mia notifications on Facebook.');
						Logger.LOG('Logged in.');
					break;
					case FB.ConnectState.appNotAuthorized:
						Logger.LOG('App is not authorized.');
					break;
					case FB.ConnectState.userNotLoggedIn:
						Logger.LOG('Not logged in.')
					break;
				}
				fixPopoverBox();
			});
		},
		login: function(callback) {			
			__FB__.connect.requireSession(
				function() {
					jQuery('#fbContent').html('Thanks!  You will receive notifications on Facebook.');
					fixPopoverBox();
				}, function() {
					jQuery('#connectNotice').text('You must connect with Mamma Mia on Facebook to receive notifications.');
				},
			false);
		}
	};
	
	var Logger = window.Logger = {
		LOG: function(msg) {
			if(/debug/.test(document.location.href) && typeof(console) != 'undefined')
				console.log(msg);
		}
	};
	
	jQuery(document).ready(function() {
		jQuery('.enableIntent').live('click', function() {
			__DC__.track();
		});
		jQuery('#connectLink').live('click', function() {
			__FB__.login();
			return false;
		});
		jQuery('#email-reminder form, #mobile-reminder form').live('submit', function(e) {
			e.preventDefault();
			return false;
		});
		jQuery('.enableReminderSubmit').live('click', function() {
			jQuery.ajax({
				'url': '/reminder.php',
				'type': 'post',
				'data': jQuery(this).parents('form').serialize(),
				'complete': function(response) {
					if(!(/must/.test(response.responseText)))
						jQuery('#popover form input').not(':submit').val('');
					
					jQuery('#reminder-msg').text(response.responseText);
					resize();
				}
			})
		});
	});
})(window, jQuery);

__FB__.init();

function resize() {
	jQuery('.background .top-side').each(function() { jQuery(this).css({ 'width': jQuery(this).parent().outerWidth() - 26 }); });
	jQuery('.background .bottom-side').each(function() { jQuery(this).css({ 'width': jQuery(this).parent().outerWidth() - 26 }); });
	
	//var __height = $('.background .right-side').parent().parent().outerHeight() - 26; /*> $(this).parent().siblings('.content').outerHeight() - 26 ?
		//$(this).parent().siblings('.content').outerHeight() - 26 :
		//$(this).parent().parent().outerHeight() - 26;*/
		
	
	jQuery('.background .right-side').each(function() {
		//console.log($(this).parent().parent().outerHeight() - 26);
		//console.log($(this).parent().siblings('.content').outerHeight() - 26);
		jQuery(this).css({'height': jQuery(this).parent().parent().outerHeight() - 26 });
	});
	jQuery('.background .left-side').each(function() { jQuery(this).css({
		'height': jQuery(this).parent().parent().outerHeight() - 26 });
	});
}

jQuery(function(){
	jQuery("#getNews").click(function(){
		emailAddress = jQuery("#newsEmailAddress").val();
		if(!emailAddress.match(/^([a-z]+[\w-]*\.?)+@([\w-]+\.)+[a-z]{2,4}$/i)){
			alert('Please enter your email address');
			return;
		}	
		startPopup('php/popover.php?type=newsletterSignup&emailAddress='+emailAddress);	
	});
	
	
});
function newsSubmit(){
	firstName = jQuery("input[name='first_name']").val();
	age = jQuery("[name='age']").val();
	gender = jQuery("[name='gender']").val();
	country = jQuery("[name='country']").val();
	state = jQuery("[name='state']").val();
	zipCode = jQuery("[name='zipCode']").val();
	haveYouSeen = jQuery("[name='haveYouSeen']").val();
	over13 = jQuery("[name='over13']").val();
	iHaveRead = jQuery("[name='iHaveRead']").val(); 
	emailAddress = jQuery("#newsEmailAddress").val();
	
	urlAddress = 'php/submitNewsletter.php?firstName='+firstName+'&age='+age+'&gender='+gender+'&country='+country+'&state='+state+'&zipCode='+zipCode+'&haveYouSeen='+haveYouSeen+'&over13='+over13+'&iHaveRead='+iHaveRead+'&emailAddress='+emailAddress;
	/* alert(urlAddress); */
	jQuery.ajax({
	  url: urlAddress,
	  success: function(data) {
	    jQuery('.popText').html(data);
	    /* alert(data); */
	  }
	});
}
function startPopup(locationTo){
jQuerydither = jQuery('<div>').attr({ id: 'dither' }).css({ opacity: 0.0 });
		jQuerypopover = jQuery('<div>').attr({ id: 'popover' }).css({ opacity: 0.0 }).append(jQuery('<div>').addClass('close').html(jQuery('<a>').attr({ href: '#' }).text('Close'))).append(jQuery('<div>').addClass('popContent'));
		jQuery('body').append(jQuerypopover).append(jQuerydither);
		jQuery('#dither').fadeTo(400, 0.6);
		jQuery('#popover').fadeTo(400, 1.0);
		// Load content 
		jQuery.ajax({
		  url: locationTo,
		  success: function(data) {
		    jQuery('#popover').html(data);
			placeSIFR('#popover h1', '#324d88');
			fixPopoverBox();
			if(jQuery('#timeline').length) {
				jQuery('#popover').css({
					marginLeft: -450,
					top: 100
				});
				window.scrollTo(0,0);
			}
			
			jQuery('#emailReminderForm').unbind('submit').submit(function(){
				var pageTracker = _gat._getTracker("UA-15588336-1");
				pageTracker._trackEvent('click', '/emailreminder');
				jQuery.ajax({
					type: 'POST',
					url: 'php/setReminder.php',
					data: 'type=email&info=' + jQuery(this).children('input[name=email]').val() + '&id=' + jQuery(this).children('input[name=eid]').val(),
					success: function(msg){
						jQuery('#emailReminderForm').html(msg);
					}
				});
				return false;
			});
			
			jQuery('#mobileReminderForm').unbind('submit').submit(function(){
				var pageTracker = _gat._getTracker("UA-15588336-1");
				pageTracker._trackEvent('click', '/mobilereminder');
				jQuery.ajax({
					type: 'POST',
					url: 'php/setReminder.php',
					data: 'type=mobile&info=' + jQuery(this).children('input[name=mobile]').val() + '&id=' + jQuery(this).children('input[name=eid]').val(),
					success: function(msg){
						jQuery('#mobileReminderForm').html(msg);
					}
				});
				return false;
			});
		  }
		});
		//jQuery('.popContent').html('stuff goes here');						
		// This resizes the overlay 
		var w_width, w_height, __iframe;
		var jQuerypopover = jQuery('#popover');
		var jQuerycontent = jQuery('#popover .popContent').length ? jQuery('#popover .popContent') : jQuery('#overlayDiv');
		var __src_height = (__iframe = jQuerycontent.find('iframe')).length ? __iframe.contents().height() : jQuerycontent.outerHeight();

		if(!jQuerypopover.length)
			return;

		w_width = jQuery(document).width() > jQuery(window).width() ? jQuery(document).width() : jQuery(window).width();
		w_height = jQuery(document).height() > jQuery(window).height() ? jQuery(document).height() : jQuery(window).height();	

		jQuery('#dither').css({ width: w_width, height: w_height });				

		if(__src_height > 700)
			jQuerycontent.css({ height: 700 });

		if(jQuery('#timeline').length) {
			//jQuerypopover.css({
			//	marginLeft: -(jQuerycontent.outerWidth() * 0.5),
			//	top: "100px"
			//});
			//window.scrollTo(0,0);
		} else {
			jQuerypopover.css({
				marginLeft: -(jQuerycontent.outerWidth() * 0.5),
				top: jQuery(window).scrollTop() + (jQuery(window).height() * 0.2) - (__src_height * 0.2)
			});
		}
		
		//end
		jQuery('#popover .close, #dither').unbind('click').click(function() {
			jQuery('#popover, #dither').fadeTo(400, 0.0, function() {
				jQuery(this).remove();
			});
			return false;
		});
}
function castGetDetail(id) {
		startPopup('php/popover.php?type=cast&id='+id);		
}
	
jQuery('.enablePopover').unbind('click').click(function() {
	startPopup('php/popover.php?type=reminder&id='+jQuery(this).attr('id'));
	return false;
});

jQuery('.enableTimeline').unbind('click').click(function() {
		startPopup('/timeline.php');
});
	
function closeButton(){
	jQuery('#popover, #dither').fadeOut().remove();
	if(jQuery("#rotatingQuote").length >0){
		jQuery("#rotatingQuote").css('display','block');
	}
}
var Flash = this.Flash = {
		place: function() {
			var flashvars = {};
			var params = { wmode: 'transparent' };
			var attributes = {};
			if(jQuery('#mediaPlayer').length)
				swfobject.embedSWF('/shell.swf', 'mediaPlayer', '650', '379', '9.0.0', '/flash/expressInstall.swf', flashvars, params, attributes);
			if(jQuery('#musicPlayer').length)
				swfobject.embedSWF('/shell2.swf', 'musicPlayer', '977', '379', '9.0.0', '/flash/expressInstall.swf', flashvars, params, attributes);
			if(jQuery('#timeline').length)
				swfobject.embedSWF('/ElegantXmlTimeline/deploy/elegant_timeline.swf', 'timeline', '900', '600', '9.0.0', '/flash/expressInstall.swf', flashvars, params, attributes);
		}
	};

Flash.place();

function fixPopoverBox() {
	var jQuerycontent = jQuery('#popover .popContent').length ? jQuery('#popover .popContent') : jQuery('#overlayDiv');
	var __src_height = jQuerycontent.outerHeight();

	if(margin_fix != 0) {
		jQuery('#popover .background .bottom-side, #popover .background .bottom-left, #popover .background .bottom-right').each(function() {
			jQuery(this).css({ 'bottom': -margin_fix });
		})
	}

	jQuery('#popover .background .right-side').each(function() { jQuery(this).css({ 'height': __src_height - 26 + margin_fix }); });
	jQuery('#popover .background .left-side').each(function() { jQuery(this).css({ 'height': __src_height - 26 + margin_fix }); });
	
	/*
	Webpage error details

	User Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0)
	Timestamp: Thu, 22 Apr 2010 07:46:19 UTC


	Message: 'null' is null or not an object
	Line: 259
	Char: 2
	Code: 0
	URI: http://mammamia.mway.situationdev.net/javascript/default.js
	*/
}

FB.Event.subscribe('edge.create', function(targetUrl) {
  _gaq.push(['_trackSocial', 'facebook', 'like', targetUrl]);
});
