(function($) {
	var User = this.User = {
		uid: null,
		session_key: null,
		secret: null,
		sig: null
	};
	
	var __FB = this.__FB = {
		comment_ids: {},
		page_id: 93298437932,
		video_id: null,
		api: null,
		connect: null,
		verifyInitialSession: function() {
			__FB.connect.ifUserConnected(function() {
				$('#facebook-connect').css({ display: 'none' });
				$('#comment-form').css({ display: 'block' });
				
				if(!(session = __FB.api.get_session()))
					return;
					
				User.uid = session.uid;
				User.session_key = session.session_key;
				User.secret = session.secret;
				User.sig = session.sig;
			});
		},
		ensureSession: function() {
			__FB.connect.get_status().waitUntilReady(function(status) {
				switch(status) {
					case FB.ConnectState.connected:
						return true;
					break;
					case FB.ConnectState.appNotAuthorized:
					case FB.ConnectState.userNotLoggedIn:
						return false;
					break;
					default:
						return false;
				}
			});
		},
		promptPermissions: function(callback) {
			__FB.connect.showPermissionDialog('publish_stream', function() {
				if(typeof callback == 'function');
					callback.call();
			});
		},
		login: function(callback) {
			__FB.connect.requireSession(function() {
				if(typeof callback != 'function')
					callback = null;
			
				__FB.api.users_hasAppPermission('publish_stream', function(has_permission) {
					if(!has_permission) {
						__FB.promptPermissions(callback);
					} else {
						$('#fan_box').html('<iframe class="FB_SERVER_IFRAME" scrolling="no" frameborder="0" src="http://www.connect.facebook.com/connect/connect.php?api_key=dd7eb81d912fba3deb27e323be9c7121&channel_url=http%3A%2F%2Fwww.hairbroadway.com%2Fxd_receiver.htm&id=93298437932&name=&width=250&connections=0&stream=0&logobar=&css=http%3A%2F%2Fwww.hairbroadway.com%2Fcss%2Fcurtain-fan.css%3Fv1.0" allowtransparency="true" name="fbfanIFrame_0" style="background:#000; border: medium none ; width: 250px; height: 65px;">');
						if(typeof callback == 'function')
							callback.call();
							
						//__FB.connect.forceSessionRefresh();
						FB.XFBML.Host.refresh();
					}
				});
			}, null, true);
		},
		logoutComplete: function() {
			$('#facebook-connect').css({ display: 'block' });
			$('#comment-form').css({ display: 'none' });
		},
		share: function(url) {
			if(__is_beta) {
				__FB.connect.showShareDialog(!!url ? url : window.location.href);
			}/* else {
				window.location.href = 'http://www.facebook.com/sharer.php?u=' + (!!url ? url : window.location.href);
			}*/
		}
	};
	
	var Dialog = this.Dialog = {
		displayFacebook: function() {
			$('#ui-video-share-more .facebook').click();
		},
		displayEmail: function() {
			$('#ui-video-share-more .email').click();
		},
		launchTwitter: function() {
			window.location.href = $('#ui-video-share-more .twitter').attr('href');
		}
	};
	
	var Video = this.Video = {
		flashvars: {
			__quality: null,
			__high: null,
			__med: null,
			__low: null
		},
		params: {
			allowFullScreen: true,
			wmode: 'transparent',
			scale: 'showall',
			bgcolor: '#000000'
		},
		attributes: {},
		placeVideo: function() {
		if(!video_ok)
			return;
			swfobject.embedSWF('/flash/hair-curtain_call-player.swf', 'ui-video-object', '622', '350', '9.0.0', "/flash/expressInstall.swf",
				Video.flashvars, Video.params, Video.attributes);
		},
		seekTo: function(time) {
			var __video_obj = $('#ui-video-object').get(0);
			__video_obj.seekTo(time);
		},
		updateTime: function(timestamp) {
			var __time_args = timestamp.split(':');
			$('#time_min').val(__time_args[0]);
			$('#time_sec').val(__time_args[1]);
			$('#time_ms').val(__time_args[2]);
		}
	};
	
	var Comment = this.Comment = {
		current_comments: {},
		getLoader: function() {
			return $('<div>').attr({ id: 'ui-loader-container'}).html(
				$('<img>').attr({ id: 'ui-comments-loading', src: 'http://static.ak.connect.facebook.com/images/loaders/indicator_white_large.gif' })
			);
		},
		getLatestComments: function() {
			(Comment.getLoader()).insertAfter('#ui-comments .ui-title');
			$.ajax({
				url: '/eparty/comments',
				data: { 'video': __FB.video_id },
				complete: function(response) {
					var $comments = $(response.responseText);
					
					$('#ui-loader-container').remove();
					
					if($comments.hasClass('ui-comment-notice'))
						return false;
					
					if(!$comments) {
						$('#ui-loader-container').css({ display: 'block' });
						return false;
					}
					
					$comments.each(function() {
						var $id;
						if(!!($id = $(this).attr('id'))) {
							$id = $id.replace('c_', '');
							$('#ui-comments .ui-comment-notice').remove();
							if(!($id in Comment.current_comments)) {
								Comment.current_comments[$id] = true;
								$(this).insertBefore('#ui-comments .ui-comment-links');
							}
						}
					});
				}
			})
		}
	};
	
	var Event = this.Event = {
		bindQualityEvents: function() {
			$('#ui-video .ui-quality a').unbind('click').click(function() {
				$(this).siblings().removeClass('active');
				$(this).addClass('active');
				Video.flashvars.__quality = $(this).text().toLowerCase();
				Video.placeVideo();
				return false;
			});
		},
		bindShareEvents: function() {
			$('#ui-video-share a').unbind('click').click(function() {
				return false;
			});
			
			$('#ui-video-share').unbind('hover').hover(
				function() {
					if(!!Share.__share_timeout)
						clearTimeout(Share.__share_timeout);

					$('#ui-video-share-more').css({ display: 'block' });
				},
				function() { Share.__share_timeout = setTimeout("$('#ui-video-share-more').css({ display: 'none' })", 500); }
			);
			
			$('#ui-video-share-more').unbind('hover').hover(
				function() {
					if(!!Share.__share_timeout)
						clearTimeout(Share.__share_timeout);
				},
				function() { Share.__share_timeout = setTimeout("$('#ui-video-share-more').css({ display: 'none' })", 500); }
			);
			
			$('#ui-video-share-more .facebook').unbind('click').click(function() {
				if(__FB.ensureSession()) {
					__FB.share();
				} else {
					__FB.login(__FB.share);
				}
				if(__is_beta || __is_beta_2)
					return false;
			});
			$('#ui-video-share-more .email').unbind('click').click(function() {
				$('#curtain-share-via_email .fb_popup, #curtain-share-via_email .fb_dialog_content').removeClass('force_315x65');
				$('#curtain-share-via_email').find('.ui-form-content').css({ display: 'block' });
				$('#curtain-share-via_email').find('.ui-form-notice').css({ display: 'none' });
				$('#curtain-share-via_email').css({ display: 'block' });
				$('#curtain-share-via_email .submit').val('Send');
			});
		},
		bindTagEvents: function() {
			$('#ui-video-tag-link').unbind('click').click(function() {
				if($(this).hasClass('active'))
					return false;
				
				$(this).addClass('active');
				$('#ui-video-tag').css({ height: 'auto' });
				$('#ui-video-tag-form').css({ display: 'block' });
					
				return false;
			});
			
			$('#tag-form').unbind('submit').submit(function() {
				$(this).find('.ui-form-submit-row input').fadeTo(300, 0.4).attr('disabled', 'disabled');
				$.ajax({
					url: '/eparty/tags/add',
					type: 'post',
					data: $(this).serialize(),
					complete: function(response) {
						$('#tag-form :input').not(':hidden').val('');
						$('#ui-video-tag-link').removeClass('active');
						$('#ui-video-tag-form').css({ display: 'none' });

						if(!response.responseText.match('error')) {
							$('#ui-video-tags .ui-video-tags').html(response.responseText);
							Event.bindTagEvents();
						}
					}
				});
				return false;
			});
			
			$('.ui-untag-link').unbind('click').click(function() {
				$('#curtain-untag').find('.ui-form-content').css({ display: 'block' });
				$('#curtain-untag').find('.ui-form-notice').css({ display: 'none' });
				$('#curtain-untag .submit').val('Yes');
				$('#curtain-untag').css({ display: 'block' });
				$('#untag-id').val($(this).attr('id').replace('i_', ''));
				window.scrollTo(0, 0);
			});
		},
		bindFacebookConnectEvents: function() {
			$('#facebook-connect-button').unbind('click').click(function() {
				__FB.login(function(response) {
					if(!response)
						return;
							
					$('#facebook-connect').css({ display: 'none' });
					$('#comment-form').css({ display: 'block' });
				});
				return false;
			});
			$('#user-info .user-meta .logout').unbind('click').click(function() {
				__FB.connect.logout(__FB.logoutComplete);
				return false;
			});
		},
		bindDateChangeEvents: function() {
			$('#ui-performance-select').unbind('change').change(function() {
				if($(this).val() == 'popup')
					return window.open('/hair/schedule', 'eparty_schedule', 'status=0, resizable=1, scrollbars=0, width=305, height=305');
				window.location.href = '/eparty/' + $(this).val();
				return false;
			});
			$('#ui-a-performance-chooser').unbind('click').click(function() {
				window.open('/hair/schedule', 'eparty_schedule', 'status=0, resizable=1, scrollbars=0, width=305, height=305');
				return false;
			});
		},
		bindCommentEvents: function() {
			$('#comment-form-object textarea').unbind('focus').focus(function() {
				if($(this).val() != 'Type a comment here...')
					return;
				$(this).text('');
			});
			$('#comment-form-object textarea').unbind('blur').blur(function() {
				if(!$(this).val().replace(/[\s]g/, '').length)
					$(this).text('Type a comment here...');
			});
		
			$('#comment-form-object').unbind('submit').submit(function() {
				var form_data = $(this).serialize() + '&s=' + User.session_key;
				
				$(this).find('.submit input').fadeTo(300, 0.4).attr('disabled', 'disabled');
				
				$.ajax({
					url: '/eparty/comments/add',
					type: 'post',
					data: form_data,
					complete: function(response) {
						var error;
					
						if(!response.responseText.match(/error/)) {
							$('#comment-form-object textarea').text('Type a comment here...');
							$('#comment-form-object .submit input').css({ opacity: 1.0 }).removeAttr('disabled');
							Comment.getLatestComments();
						} else {
							error_code = response.responseText.replace('error:', '').replace(/[^a-z]/g, '');
							error_msg = Error.dictionary[error_code];

							if(!error_msg)
								error_msg = Error.dictionary['500'];
							
							$('#comment-form-errors').text(error_msg);
							$('#comment-form-object .submit input').fadeTo(300, 1.0).removeAttr('disabled');
						}
					}
				});
				return false;
			});
		},
		bindFbPopoverEvents: function() {
			$('.ui-fb-popover .fb_pop_content .ui-dialog-control .submit').unbind('click').click(function() {
				$(this).val('One moment...').attr({ 'disabled': 'disabled' });
				$.ajax({
					url: $(this).parents('form').attr('action'),
					data: $(this).parents('form').serialize(),
					type: 'post',
					complete: function(response) {
						$('.ui-fb-popover .submit').removeAttr('disabled');
						$('#RES_ID_fb_pop_dialog_table').css({ height: 75 });
						$('.ui-fb-popover').each(function() {
							if($(this).css('display' != 'none')) {
								if($(this).attr('id') == 'curtain-share-via_email')
									$('#curtain-share-via_email .fb_popup, #curtain-share-via_email .fb_dialog_content').addClass('force_315x65');
									
								$(this).find('.ui-form-content').css({ display: 'none' });
								$(this).find('.ui-form-notice').css({ display: 'block' });
							}
						});
					}
				});
			});
			$('.ui-fb-popover .fb_pop_content .ui-dialog-control .cancel, .ui-fb-popover .fb_dialog_cancel_button').unbind('click').click(function() {
				$(this).parents('.ui-fb-popover').css({ display: 'none' });
			});
		}
	};
	
	var Share = this.Share = {
		__share_timeout: null,
		__url: null
	};
	
	var Error = this.Error = {
		dictionary: {
			'nofan': "You must be a fan of HAIR on Facebook to comment.  Please click the 'Become a Fan' button above.",
			'500': 'Something went wrong - please try to submit your comment again.' 
		}
	};
	
	// auth (FYI only)
	//__FB.connect.showPermissionDialog('read_stream', function() {}, true, [68789521058]);
	
	$(document).ready(function() {		
		FB_RequireFeatures(['Connect'], function() {
			FB.init('dd7eb81d912fba3deb27e323be9c7121', '/xd_receiver.htm');
			__FB.connect = FB.Connect;
			__FB.api = FB.Facebook.apiClient;
			__FB.verifyInitialSession();

			if(__is_beta)
				__FB.connect.showShareDialog(window.location.href);
				
			if(__is_beta_2)
				__FB.connect.showShareDialog();
		});
				
		Comment.getLatestComments();
		Video.placeVideo();
		
		Event.bindQualityEvents();
		Event.bindShareEvents();
		Event.bindTagEvents();
		Event.bindDateChangeEvents();
		Event.bindFacebookConnectEvents();
		Event.bindCommentEvents();
		Event.bindFbPopoverEvents();
	});
})(jQuery);
