// Intercept clicks to exclusive links and show little ajax layers.
var ExclusiveLinks; // Globally scoped variable that can be used by other files
(function($) {
	$(document).ready(function() {

		//$.addStylesheet('popups/flyouts/owners');

		var OwnerLayer = function(node, keepOld, e) {
			var div = node;
			var bottom = 0;
			var content;
			var id = new Date().getTime();
			var event = e;
			var init = function() {
				if (keepOld === false) {
					$('div.exclusive-layer').remove();
				}
				div =  $(['<div id="owner-layer', id, '" class="exclusive-layer"><div id="owner-body"><div id="owner-header"><img id="close-button" alt="close" src="/consumer/images/header/close_blue.gif" /></div><div id="owner-content"></div></div><div id="owner-bottom"> </div></div>'].pack());
				content = div.find('#owner-content');
				div.css({
					position: 'absolute',
					marginLeft: 0,
					top: node.offset().top - 20,
                    zIndex: 5000
				}).hide();
				$('body').append(div);
				div.find('#close-button').click(function() {
					$.showSelects();
					div.remove();
				});
			}();
			return {
				addContent: function(text) {
					var layer = div;
					var before = div.height();
					var beforew = div.width();
					if (typeof text === 'object') {
						content.html(text);
					} else {
						content.text(text);
					}
					ec();
					var after = div.height();
					var afterw = div.outerWidth(true);
					var top = parseInt(layer.css('top'));
					var left = parseInt(layer.css('left'));

					layer.css({
						top: top - (after - before) - 10
					}).show();

					var max = 0;
					var maxh = 0;
					content.children().each(function() {
						var node = $(this);
						if (node.outerWidth() > max) {
							max = node.outerWidth(true);
						}
						if (node.outerHeight() > maxh) {
							maxh = node.outerHeight(true);
						}
					})
					div.width(max);
					var left = event.pageX - (max / 2);
					div.css({
						left: left
					});
					$('#owner-bottom').width(max).css({backgroundPosition: '50% 0%'});

					var body = $('#wrapper');
                    if (body.length < 1) {
                        body = $('#pageBody');
                    }
					var position = body.position();
					var bodyLeft = position.left;
					var bodyRight = bodyLeft + body.width();
                    var bodyTop = position.top;

					var divLeft = left;
					var divRight = left + div.width();
                    var divTop = div.position().top;


                    var bottom = $('#owner-bottom');
					var middle = divLeft + (div.width() / 2);

                    var correctionsMade = false;
                    var corrections = {

                    };
					if (divLeft < bodyLeft) {
						var offset = bodyLeft - Math.abs(divLeft);
						middle += offset;
						div.css({
							left: bodyLeft
						});
                        correctionsMade = true;
					}

					if (divRight > bodyRight) {
						var offset = divRight - bodyRight;
						middle -= offset;
						div.css({
							left: parseInt(div.css('left'), 10) - offset
						});
                        correctionsMade = true;
					}

                    if (divTop < 0) {
                        div.css({
                            top: '5px'
                        });
                        correctionsMade = true;
                    }
                    
					$.hideSelects(layer);
					layer.find('#what-is-this').click(function(e) {
						var a = $(this);
						$.get(a.attr('href'), {}, function(data) {
							var newlayer = new OwnerLayer(a, true, e);
							var di = $('<div class="content-item">');
							di.append(data);
							newlayer.addContent(di);
						})
						return false;
					});

					if ($('#upgrade-button').exists()) {
						var button = $('#upgrade-button');
						var parent = button.parents('div:first');
						var w = button.outerWidth(true);
						var pw = parent.innerWidth(true);
						var x = (pw - w) / 2 - (parseInt(button.css('padding-left'), 10) * 2);
						button.css('margin-left', x.pixelate());

					}

					layer.find("#username").blur(function() {
						layer.find("#password").focus();
					});

					layer.find('#username, #password').keydown(function(e) {
						if (e.keyCode == 13) {
							$('#login-button').click();
							return false;
						}
					})

					$('#login-button').click(function() {
						var button = $(this);
						button.text("Logging in...");
						var form = $(this).parents('form:first');
						form.submit(function() {
							var inputs = form.find(':input');
							var qs = {};
							inputs.each(function(i) {
								qs[$(this).attr('name')] = $(this).val();
							});
							$.ajax({
								type: 'POST',
								url: form.attr('action'),
								data: qs,
								cache: false,
								error: function(xhr, status, errorThrown) {
									// This actually isn't an error, it's the 503 redirect
									// when login succeeds
									window.location = window.location.href;
								},
								success: function(data) {
									// This is actually the error because it sends HTML
									// back to the browser
									if (data) {
										if (data.match(/login\-error\-list/)) {
											button.text("Login");
											$('#error-area').empty().html(data);
										} else {
											window.location = window.location.href;
										}
									}
								}
							})
							return false;

						}).submit();
						return false;
						//$('#login-submit-button').click();
					})



				},
				remove: function() {
					Viking.show_selects();
					$('#owner-layer').remove();
				}
			}
		};

		var listen = function() {
			$('.exclusive-layer #username, .exclusive-layer #password').focus(function() {
				$(this).val('');
			});
		}

		ExclusiveLinks = function() {
			return {
				scan: function() {
					$('a.exclusive').click(function(e) {
						var a = $(this);
						var href = a.attr('href');
						if (!href.match(/\/popups\/flyouts\/owners\//)) {
							return true;
						} else {

							$.get(a.attr('href'), {}, function(data) {
								var html = $(data);
								var layer = new OwnerLayer(a, false, e);
								layer.addContent(html);
								listen();
								$('#close-button').click(function() {
									layer.remove();
								});
							});
						}
						return false;
					});
				}
			}
		}();
		ExclusiveLinks.scan();

		if (window.location.hash.match(/autofire/)) {
			$('#username, #password').focus(function() {
				$(this).val('');
			});
			$('#login-button').click(function() {
				var button = $(this);
				button.text("Logging in...");
				var form = $(this).parents('form:first');
				form.submit(function() {
					var inputs = form.find(':input');
					var qs = {};
					inputs.each(function(i) {
						qs[$(this).attr('name')] = $(this).val();
					});
					$.ajax({
						type: 'POST',
						url: form.attr('action'),
						data: qs,
						cache: false,
						error: function(xhr, status, errorThrown) {
							// This actually isn't an error, it's the 503 redirect
							// when login succeeds
							window.location = '/consumer/index.jsp';
						},
						success: function(data) {
							// This is actually the error because it sends HTML
							// back to the browser
							if (data) {
								if (data.match(/login\-error\-list/)) {
									button.text("Login");
									$('#error-area').empty().html(data);
								} else {
									window.location = window.location.href;
								}
							}
						}
					})
					return false;

				}).submit();
                $('#exclusive-register-flyout').css('width', '500px');
			})
		}

		// Activate legend if there are exclusive links on the page.
		if ($('a.exclusive').length > 0) {
			$('div.ownersExclusiveLegend').show();
		}
	});
})(jQuery);