document.observe('dom:loaded', function() {
	
	//This needs to be included inside of a dom:loaded event
var modModal = Class.create({
	initialize: function(control, href, title, width, obj, allowReopen) {
		this.control = control;
		this.href = href;
		this.title = title;
		this.borderWidth = 6;
		this.isOpen = false;
		this.width = width;
		this.obj = obj;
		this.allowReopen = allowReopen;
		
		//create elements
		this.modalFrame = new Element('div', {'class': 'mod-modal-frame'});
		this.modalWindow = new Element('div', {'class': 'mod-modal-container'}).update("<h3>Loading...</h3>");
		this.header = new Element('div', {'class': 'mod-modal-header'}).update(this.title);
		
		this.content = new Element('div', {'class': 'mod-modal-content'});
		this.cancelBtn = new Element('a', {'class': 'close-button', title: 'Close Modal Window'}).update('Close');
		this.cancelBtn.setStyle({'marginTop': '2px'});
		
		this.modalFrame.style.visibility = 'hidden';
		this.modalWindow.style.visibility = 'hidden';
		
		this.getSrc();			
	},
	getSrc: function() {
		that = this;
		this.modalWindow.update('');
		
		new Ajax.Updater(that.content, that.href, {
			method: 'get',
			evalScripts: true, 
			onComplete: function() {
				that.go();
			}		
		});
	},
	go: function() {
		var that = this;
		var otherThing = this;
		
		document.body.appendChild(this.modalFrame);
		document.body.appendChild(this.modalWindow);
		
		this.modalWindow.appendChild(this.cancelBtn);
		this.modalWindow.appendChild(this.header);
		this.modalWindow.appendChild(this.content);
		
		if (this.width != null) this.modalWindow.style.width = this.width + 'px';
		
		var offsetY = document.viewport.getScrollOffsets()[1];
		var windowDimensions = this.modalWindow.getDimensions();
		
		//calculate modal frame width
		var frameDimensions = new Object();
		frameDimensions.width = parseInt(this.modalWindow.getWidth()) + (2 * parseInt(this.borderWidth));
		frameDimensions.height = parseInt(this.modalWindow.getHeight()) + (2 * parseInt(this.borderWidth));
		
		//calculate positioning
		var top = new Object();
		top.frame = parseInt(offsetY) + 120 - parseInt(this.borderWidth);
		top.modal = parseInt(offsetY) + 120;
		
		var left = new Object();
		left.frame = -(parseInt(this.modalWindow.getWidth()) + (2 * parseInt(this.borderWidth))) / 2;
		left.modal = -parseInt(this.modalWindow.getWidth()) / 2;
		
		this.modalFrame.setStyle({
			width: frameDimensions.width + 'px', 
			height: frameDimensions.height + 'px',
			top: top.frame + 'px',
			marginLeft: left.frame + 'px',
			display: 'none',
			visibility: 'visible'
		});
		
		this.modalWindow.setStyle({
			top: top.modal + 'px',
			marginLeft: left.modal + 'px',
			display: 'none',
			visibility: 'visible'
		});
		
		if (this.control != null)
		{
			this.control.observe('click', function() {
				if (that.isOpen)
					that.close();
				else {
					that.open();
				}
				if (!that.allowReopen) {
					that.control.stopObserving('click');
					that.control.style.cursor = 'auto';
				}
			});
		}
		
		this.cancelBtn.observe('click', function() {
			that.close();
		});
	},
	open: function() {
		new Effect.Appear(this.modalFrame, { from: 0, to: 0.3, duration: 0.3 });
		new Effect.Appear(this.modalWindow, { from: 0, to: 1, duration: 0.3});
		this.isOpen = true;
		if (this.obj != false)
			this.obj.callBack();
	},
	close: function() {
		new Effect.Fade(this.modalFrame, { from: 0.3, to: 0, duration: 0.3 });
		new Effect.Fade(this.modalWindow, { from: 1, to: 0, duration: 0.3 });
		this.isOpen = false;
	},
	resizeFrame: function() {
		var offsetY = document.viewport.getScrollOffsets()[1];
		//calculate modal frame width
		var frameDimensions = new Object();
		frameDimensions.width = parseInt(this.modalWindow.getWidth()) + (2 * parseInt(this.borderWidth));
		frameDimensions.height = parseInt(this.modalWindow.getHeight()) + (2 * parseInt(this.borderWidth));
		//calculate positioning
		var top = new Object();
		top.frame = parseInt(offsetY) + 120 - parseInt(this.borderWidth);		
		var left = new Object();
		left.frame = -(parseInt(this.modalWindow.getWidth()) + (2 * parseInt(this.borderWidth))) / 2;
		this.modalFrame.setStyle({
			width: frameDimensions.width + 'px', 
			height: frameDimensions.height + 'px',
			top: top.frame + 'px',
			marginLeft: left.frame + 'px'
		});
	}
});
	
	$('coupon-offer').clonePosition($('coupon-container'));
	
	var validate = {};
	validate.callBack = function () {		
		
		var loggedInUser = $('loggedInUser').value;
		var isGift = $('isGift').value;
		
		var errors = {
			firstName: "Please enter your first name.",
			lastName: "Please enter your last name",
			email: "Please enter your email.",
			verifyEmail: "Emails do not match."
		};
		
		var errorsGift = {
			recFirstName: "Recipient first name cannot be left blank.",
			recLastName: "Recipient last name cannot be left blank."
		}
		
		
		if (loggedInUser == "true") {
			$('is-upgrade').value = "true";
			$('name-fields').addClassName('hide');
			$('email-fields').addClassName('hide');
			modal.resizeFrame();
		} else if (isGift == "true") {			
			$('name-fields').addClassName('hide');
			$('email-fields').addClassName('hide');
			modal.resizeFrame();
		}
		
		var errorsPassword = {
			pass: "Password cannot be left blank.",
			verify: "Verify Password cannot be left blank."
		}
		
		if (loggedInUser == "true") {
			$('create-password').setStyle({
				position: 'absolute',
				top: '-500px',
				left: '-500px',
				visibility: 'hidden',
				zIndex: 1000
			});
			errorsPassword = {};
			modal.resizeFrame();
		}
		
		var errorsBilling = {
			name: "Name cannot be left blank.",
			address: "Address cannot be left blank.",
			city: "City cannot be left blank.",
			state: "State/Province/Region cannot be left blank.",
			zip: "Zip/Postal Code cannot be left blank.",
			cc: "Credit card number cannot be left blank.",
			ccv: "CCV cannot be left blank."
		}
		
		var fields = $('mod-form').getElementsBySelector('input');
		var emailFilter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/; 
		
		fields.each(function(el, i) {
			var parent = el.ancestors()[0];
			el.observe('focus', function(e) {
				parent.addClassName('active-row');
			});
			//really ugly form validation
			el.observe('blur', function(e) {
				switch(i) {
				case 2:
					if (el.value.length < 1) {
						el.addClassName('invalid');
						errors.firstName = "Please enter a valid first name.";
					} else {
						el.removeClassName('invalid');
						errors.firstName = "";
					}
					break;
				case 3:
					if (el.value.length < 1) {
						el.addClassName('invalid');
						errors.lastName = "Please enter a valid last name.";
					} else {
						el.removeClassName('invalid');
						errors.lastName = "";
					}
					break;
				case 4:
					var emailAddress = el.value;
					if (el.value.length < 5 || !emailFilter.test(el.value)) {
						el.addClassName('invalid');
						errors.email = "Please enter a valid email.";
					} else {
						el.removeClassName('invalid');
						errors.email = "";
					}
					params = '["' + el.value + '"]';
					callStringMethod (
						'isModAccount',
						params,
						function(response) {
							if (response == "true" || response == "paid" || response == "unverified") {
								$('next-page-1').update('You must sign in to continue.');
								$('next-page-1').disabled = true;
								var handleLogin = {};
								handleLogin.callBack = function() {
									$('simple-login-email').value = emailAddress;
									$('simple-login-email').disabled = true;
									setTimeout(function(){
										$('simple-login-password').focus();
									}, 600);
									$('simple-login-submit').observe('click', function() {
										new Ajax.Request('/dyn/json?email='+$('simple-login-email').value+'&password='+$('simple-login-password').value+'&url=noredirect', {
										      method: 'post',
										      postBody: '["login",[]]',
										      onSuccess: function(transport) {
											  	  var response = transport.responseText;
											  	  if (response == '["Failure"]') {
											  		  alert('Invalid password.');
											  	  } else {
											  		  window.location.href = "/dyn/actions/viewHolidaySpecial?repaint=true";
											  	  }
										      },
										      onFailure: function() { 
										    	  alert("There was an error with the connection"); 
										    }
										  });
									});
								}
								var upgrade = confirm("This email already exists in our database. If you want to upgrade this account, press ok to continue.");
								if (upgrade) {
									modal.close();
									loginModal = new modModal(null, "/html/simple-login-form.html", "Holiday Special - Please Log In", 400, handleLogin, false);
									setTimeout(function() {
										loginModal.open();
									}, 600);
										
								}
							} else {
								$('next-page-1').disabled = false;
								$('next-page-1').update("Next &raquo;");
							}
						},
						function(error) {},
						function() {}
					);	


					break;
				case 5:
					if (el.value != fields[4].value) {
						el.addClassName('invalid');
						errors.verifyEmail = "Emails do not match.";
					} else {
						el.removeClassName('invalid');
						errors.verifyEmail = "";
					}
					break;
				case 6:
					if (fields[0].checked) {
						if (el.value.length < 1) {
							el.addClassName('invalid');
							errorsGift.recFirstName = "Please enter a valid first name for the recipient.";
						} else {
							el.removeClassName('invalid');
							errorsGift.recFirstName = "";
						}
					}
					break;
				case 7:
					if (fields[0].checked) {
						if (el.value.length < 1) {
							el.addClassName('invalid');
							errorsGift.recLastName = "Please enter a valid last name for the recipient.";
						} else {
							el.removeClassName('invalid');
							errorsGift.recLastName = "";
						}
					}
					break;
				case 8:
					if (!fields[0].checked) {
						if (el.value.length < 6) {
							el.addClassName('invalid');
							errorsPassword.pass = "Password must contain at least 6 characters.";
						} else {
							el.removeClassName('invalid');
							errorsPassword.pass = "";
						}
					}
					break;
				case 9:
					if (!fields[0].checked) {
						if (el.value != fields[9].value) {
							el.addClassName('invalid');
							errorsPassword.verify = "Passwords do not match.";
						} else {
							el.removeClassName('invalid');
							errorsPassword.verify = "";
						}
					}
					break;
				case 10:
					if (el.value.length < 3) {
						el.addClassName('invalid');
						errorsBilling.name = "Please enter a billing name.";
					} else {
						el.removeClassName('invalid');
						errorsBilling.name = "";
					}
					break;
				case 11:
					if (el.value.length < 5) {
						el.addClassName('invalid');
						errorsBilling.address = "Please enter a valid billing address.";
					} else {
						el.removeClassName('invalid');
						errorsBilling.address = "";
					}
					break;
				case 13:
					if (el.value.length < 1) {
						el.addClassName('invalid');
						errorsBilling.city = "Please enter a valid city.";
					} else {
						el.removeClassName('invalid');
						errorsBilling.city = "";
					}
					break;
				case 14:
					if (el.value.length < 2) {
						el.addClassName('invalid');
						errorsBilling.state = "Please enter a valid state.";
					} else {
						el.removeClassName('invalid');
						errorsBilling.state = "";
					}
					break;
				case 15:
					if (el.value.length < 5) {
						el.addClassName('invalid');
						errorsBilling.zip = "Please enter a valid zip/postal code.";
					} else {
						el.removeClassName('invalid');
						errorsBilling.zip = "";
					}
					break;
				case 16:
					if (el.value.length < 16) {
						el.addClassName('invalid');
						errorsBilling.cc = "Please enter a valid credit card number.";
					} else {
						el.removeClassName('invalid');
						errorsBilling.cc = "";
					}
					break;
				case 17:
					if (el.value.length < 3) {
						el.addClassName('invalid');
						errorsBilling.ccv = "Please enter a valid credit card verification (CCV) number.";
					} else {
						el.removeClassName('invalid');
						errorsBilling.ccv = "";
					}
					break;
				}		
				
				parent.removeClassName('active-row');
			});
		});
		
		$('gift-yes').observe('click', function(e) {
			isGift = "true";
			if ($('gift-fields').style.display == 'none') {
				Effect.BlindDown('gift-fields', { duration: 0.5 });
			}
			if ($('not-gift-fields').style.display != 'none') {
				Effect.BlindUp('not-gift-fields', { duration: 0.5 });
			}
			$('plan-details').update('(One year, does not automatically renew)');
			if (loggedInUser == "true") {
				$('name-fields').addClassName('hide');
				$('email-fields').addClassName('hide');
			}
			setTimeout(function() {
				modal.resizeFrame();
			}, 600);
		});
		
		$('gift-no').observe('click', function(e) {
			isGift = "false";
			if ($('not-gift-fields').style.display == 'none') {
				Effect.BlindDown('not-gift-fields', { duration: 0.5 });
			}
			if ($('gift-fields').style.display != 'none') {
				Effect.BlindUp('gift-fields', { duration: 0.5 });
			}
			$('plan-details').update('(One year, automatically renews)');
			if (loggedInUser == "false") {
				$('name-fields').removeClassName('hide');
				$('email-fields').removeClassName('hide');
			}
			setTimeout(function() {
				modal.resizeFrame();
			}, 600);
		});
		
		$('next-page-1').observe('click', function() {
			var valid = true;
			var errorsStr = "";
			if (isGift == "true") {
				for (var i in errorsGift) {
					if (errorsGift[i] != "") {
						valid = false;
						errorsStr += errorsGift[i] + "\n";
					}
				}
			} else if (loggedInUser == "false") {
				for (var i in errors) {
					if (errors[i] != "") {
						valid = false;
						errorsStr += errors[i] + "\n";
					}
				}
			}
			if (valid) {
			 	$('page-1').style.display = 'none';
				$('page-2').style.display = 'block';
				if (!$('gift-yes').checked) { $('create-password').style.display = 'block'; }
				setTimeout(function() {
					modal.resizeFrame();
				}, 600);
			} else {
				alert(errorsStr);
			}
		});
		
		$('next-page-2').observe('click', function() {
			var errorString2 = "";
			var valid = true;
			for (var i in errorsBilling) {
		        if (errorsBilling[i] != "")
		            valid = false;
		    }
		    if (isGift == "false") {
		    	for (var i in errorsPassword) {
		            if (errorsPassword[i] != "")
		                valid = false;
		        }
		    }
		    
		    if ($('expMonth').value == "" || $('expYear').value == "") {
				valid = false;
		    }
		    
			if (valid) {
				$('register-form').submit();
			} else {
				if (isGift == "false") {
					for (var i in errorsPassword) {
						if (errorsPassword[i] != "") {
							errorString2 += errorsPassword[i] + "\n";
						}
					}
				}
				for (var i in errorsBilling) {
					if (errorsBilling[i] != "") {
						errorString2 += errorsBilling[i] + "\n";
					}
				}
				
				if ($('expMonth').value == "" || $('expYear').value == "") {
			    	errorString2 += "Please enter a valid expiration date.";
			    }
				
				alert(errorString2);
			}
		});
		
		$('prev-page-2').observe('click', function() {
			$('page-1').style.display = 'block';
			$('page-2').style.display = 'none';
			$('create-password').style.display = 'none';
			setTimeout(function() {
				modal.resizeFrame();
			}, 600);
		});
		
		
		function isNumberKey(evt)
		{
		   var charCode = (evt.which) ? evt.which : event.keyCode
		   if (charCode > 31 && (charCode < 48 || charCode > 57))
		      return false;
		
		   return true;
		}
	}
	
	modal = new modModal($('coupon-container'), "/dyn/actions/viewHolidaySpecialForm", "Holiday Special - Sign Up", 425, validate, false);
		
	if (isRepaint == 'true') {
		setTimeout(function() {
			modal.open();
			setTimeout(function(){
				$('gift-yes').checked = false;
				$('gift-no').checked = true;
				$('gift-fields').hide();
				$('not-gift-fields').show();
				$('plan-details').update('(One year, automatically renews)');
				setTimeout(function() {
					modal.resizeFrame();
				}, 600);
			}, 600);
		}, 600);
	}
	

});
