window.addEvent("domready", function()
{
	var Register = new Class({

		initialize: function(element) 
		{
			this.form = $(element);
			if(this.form)
			{
				this.form.set('send',
				{
					onSuccess: function(responseText, responseXML) 
					{
						if(responseText.length == 0)
						{
							alert("Thank you for registering");
							location.href = "/battles";
						}
						else
						{
							alert(responseText);
						}
					},
					onFailure: function()
					{
						alert("Sorry there was an error processing your request. Please try again later");
					}
				});
				
				this.form.addEvent('submit', function(event)
				{
					event.stop();
					var firstname = this.form.getElement("input[name=firstname]");
					if(this.trim(firstname.value).length == 0)
					{
						alert("Please enter a valid first name");
						return;
					}

					var lastname = this.form.getElement("input[name=lastname]");
					if(this.trim(lastname.value).length == 0)
					{
						alert("Please enter a valid last name");
						return;
					}

					var address = this.form.getElement("input[name=address]");
					if(this.trim(address.value).length == 0)
					{
						alert("Please enter a valid address");
						return;
					}

					var city = this.form.getElement("input[name=city]");
					if(this.trim(address.value).length == 0)
					{
						alert("Please enter a valid city or town");
						return;
					}

					var zip = this.form.getElement("input[name=zip]");
					if(this.trim(zip.value).length == 0 || !(new RegExp("^\\d{5}([\\-]\\d{4})?$").test(zip.value)))
					{
						alert("Please enter a valid zip code");
						return;
					}
					
					var email = this.form.getElement("input[name=email]");
					if(!this.isValidEmail(email.value))
					{
						alert("Please enter a valid email address");
						return;
					}

					var year = this.form.getElement("select[name=year]");
					if(year.selectedIndex == 0 )
					
					{
						alert("Please select your year of birth");
						return;
					}
					
					var tiebreaker = this.form.getElement("input[name=tiebreaker]");
					if(tiebreaker.value.length == 0 || !(new RegExp("^[1-9]\\d*$").test(tiebreaker.value)))
					{
						alert("Please enter a valid number of votes");
						return;
					}
					
					var magazine = this.form.getElement("select[name=magazine-subscriber]");
					if(magazine.selectedIndex == 0)
					{
						alert("Please select a response for \"Are you a Complex Magazine subscriber?\"");
						return;
					}				
					
					
					this.form.send();
				}.bind(this));
				
				var list = $$("div.introduction");
				if(list && list.length>0)
				{
					var container = new Element("p");
					container.inject(list[0]);
					container.appendText("Or ");
					new Element("a",
					{
						"href": "#",
						"html": "login",
						"events": {
							"click": function(event)
							{
								event.stop();
								var email = prompt("Please enter the email address you used to register:");
								if(email && email.length > 0)
								{
									if(this.isValidEmail(email))
									{
										this.doLogin(email);
									}
									else
									{
										alert("Sorry invalid email address");
									}
								}
							}.bind(this)
						}
					}).inject(container);
					container.appendText(", if you have already registered.");
					new Element("a")
					
				
				}
				
				
				
				
				
				this.form.action = "/register";
				this.form.setStyle("display","block");
			}
		},
		
		isValidEmail: function(text)
		{
			return text.length > 0 && new RegExp("\\w+([-+.']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*").test(text); 
		},
		
		trim: function (text) {
			return text.replace(new RegExp("^\\s+", "g"), "").replace(new RegExp("\\s+$", "g"), "");
		},
		
		isValidDate: function(day, month, year)
		{
			day = parseInt(day);
			month = parseInt(month);
			year = parseInt(year)
			var date = new Date(year, month-1, day);
			alert(date.toDateString());
			return (date.getMonth() == (month-1));
		},
		
		getSelectValue: function(select)
		{
			return select.options[select.selectedIndex].value;
		},
		
		doLogin: function(email)
		{
			new Request(
			{
				method: "post", 
				url: "/login",
				onSuccess: function(responseText, responseXML)
				{
					if(responseText && responseText.length >0)
					{
						alert(responseText);
					}
					else
					{
						alert("You are now logged in.");
						location.href = "/battles";
					}
				}.bind(this),
				onFailure: function()
				{
					alert("Sorry there was an error processing your request. Please try again later");
				}
			}).send("email=" + email);
		}
	});
	
	
	
	var Battle = new Class({
		initialize: function(element) 
		{
	
			this.form = $(element);
			this.login = $("login");
			if(this.form)
			{
				this.next = this.form.getElement("input[name=next]").value;
				this.voteid = this.form.getElement("input[name=vote-id]").value;
				
				var layers = this.form.getElements("div.overlay");
				if(layers && layers.length == 2)
				{
					if(this.voteid.length>0 && parseInt(this.voteid) >0)
					{
						this.createButton(layers[0], this.form.getElement("input[name=lhs-id]").value);
						this.createButton(layers[1], this.form.getElement("input[name=rhs-id]").value);
					}
					else
					{
						this.createClosedButton(layers[0]);
						this.createClosedButton(layers[1]);
					}
				}

				if(this.login && !this.isLoggedIn())
				{
				
					this.login.set('send',
					{
						onSuccess: function(responseText, responseXML) 
						{
							if(responseText && responseText.length >0)
							{
								alert(responseText);
							}
							else
							{
								this.login.setStyle("display","none");
								this.loginfield.value = "1";
								alert("You are now logged in.");
							}
						}.bind(this),
						onFailure: function()
						{
							alert("Sorry there was an error processing your request. Please try again later");
						}
					});
					
					this.login.addEvent('submit', function(event)
					{
						event.stop();
						var email = this.login.getElement("input[name=email]");
						if(this.trim(email.value).length == 0)
						{
							alert("Please enter the email address you used to register");
							return;
						}
						else if(!this.isValidEmail(email.value))
						{
							alert("Sorry invalid email address");
							return;
						}
						else
						{	
							this.login.send();
						}
					}.bind(this));
					this.login.setStyle("display","block");
				}
			}
			
		},
		
		isLoggedIn: function()
		{
			return /STYLEWAR\=/.test(document.cookie);
		},
		
		isValidEmail: function(text)
		{
			return text.length > 0 && new RegExp("\\w+([-+.']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*").test(text); 
		},
		trim: function (text) {
			return text.replace(new RegExp("^\\s+", "g"), "").replace(new RegExp("\\s+$", "g"), "");
		},
		
		createButton: function(parent, id)
		{
			new Element("input",
			{
				"type": "button",
				"events": 
				{
					"click": function(event, id)
					{
						event.stop();
						this.post(id);
					}.bindWithEvent(this, id)
				}
			}).inject(parent);
		},

		createClosedButton: function(parent)
		{
			new Element("input",
			{
				"type": "button",
				"events": 
				{
					"click": function(event)
					{
						event.stop();
						if(confirm("Voting currently closed. Continue to the next Battle?"))
						{
							this.nextPage();
						}
					}.bind(this)
				}
			}).inject(parent);
		},

		
		post: function(id) 
		{
			if(this.isLoggedIn())
			{
				new Request(
				{
					method: "post", 
					url: this.form.action,
					onSuccess: function(responseText, responseXML)
					{
						if(responseText && responseText.length >0)
						{
							alert(responseText);
						}
						else
						{
							$$('body').adopt(new Element('div',
							{
								'styles':{
									'position':'fixed',
									'top': 0,
									'left': 0,
									'bottom': 0,
									'right': 0,
									'opacity': 0.75,
									'z-index': 1000,
									'background-color':'#000000'
								}
							}));
							
							$$('body').adopt(new Element('h3',
							{
								'styles':{
									'position':'fixed',
									'top': '50%',
									'left': 0,
									'width': '100%',
									'height':100,
									'text-align': 'center',
									'z-index': 2000,
									'top-margin': -100,
									'left-margin': -200
								},
								'html': "Your Vote Has Been Recorded. Thank You!"
							}));
							this.nextPage.delay(2000);
						}
					}.bind(this),
					onFailure: function()
					{
						alert("Sorry there was an error processing your request. Please try again later");
					}
				}).send("voteid=" + this.voteid + "&candidateid=" + id);
			}
			else
			{
				alert("Please register or login to vote");
			}
		},
		
		nextPage: function()
		{
			var list = $$("input[name=next]");
			var next = (list.length>0)?list[0].value: "/battles";
			location.href = next;
		}
	});

	// Subscribe Form
	var Subscribe = new Class({
		initialize: function(element) 
		{
			var message = "JOIN OUR NEWSLETTER";
			var panel = $(element);
			if(panel)
			{
				// Setup form
				var form = new Element("form",
				{
					method: "post"
				});
				form.inject(panel);
				
				// Setup Email
				var email = new Element("input",
				{
					type: "text",
					name: "email",
					name: "email",
					maxlength: 55,
					size: 30,
					value: "JOIN OUR NEWSLETTER"
				});
				
				email.addEvent("focus", function()
				{
					if(this.value == message)
					{
						this.value="";
					} 
					else 
					{
						this.select();
					}
				}.bind(email));
	
				email.addEvent("blur", function()
				{
					if(this.value=="")
					{
						this.value=message;
					}
				}.bind(email));
				email.inject(form);
				
				new Element("input",
				{
					type: "submit",
					title: "SUBSCRIBE",
					value: "SUBSCRIBE"
				}).inject(form);
				
				
				form.addEvent('submit', function(event)
				{
					event.stop();
					if(this.value.length>0 && /\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/.test(this.value))
					{
						new Request(
						{
							method: "post", 
							url: "/subscribe",
							onSuccess: function(responseText, responseXML)
							{
								if(responseText && responseText.length >0)
								{
									alert(responseText);
								}
								else
								{
									alert("Thankyou for subscribing to Complex Newsletter");
								}
							}.bind(this),
							onFailure: function()
							{
								alert("Sorry there was an error processing your request. Please try again later");
							}
						}).send("email=" + this.value);

					}
					else
					{
						alert("Please enter a valid email address");
					}
				}.bind(email));


				var policy = new Element("span",
				{
					"class": "policy",
					"html": "By pressing Subscribe you agree to our "
				});
				
				policy.inject(form);
 
 
 
 				new Element("a",
				{
					href: "http://www.complex.com/Corporate/Privacy-Policy",
					html: "privacy policy",
					events:
					{
						click: function(event){
							event.stop();
							this.popup("http://www.complex.com/Corporate/Privacy-Policy","Privacy Policy","500","500","yes","center");
						}.bind(this)
					}	
				}).inject(policy);
 			}
			
		},
		
		
		popup: function (mypage, myname, w, h, scroll, pos, resize) 
		{
		    if (pos == "random") {
		        LeftPosition = screen.width ? Math.floor(Math.random() * (screen.width - w)) : 100;
		        TopPosition = screen.height ? Math.floor(Math.random() * ((screen.height - h) - 75)) : 100;
		    }
		    if (pos == "center") {
		        LeftPosition = screen.width ? (screen.width - w) / 2 : 100;
		        TopPosition = screen.height ? (screen.height - h) / 2 : 100;
		    } else if (pos != "center" && pos != "random" || pos == null) {
		        LeftPosition = 0;
		        TopPosition = 20;
		    }
		    
		    settings = "width=" + w + ",height=" + h + ",top=" + TopPosition + ",left=" + LeftPosition + ",scrollbars=" + scroll + ",resizable=" + resize + ",location=no,directories=no,status=no,menubar=no,toolbar=no";
		    win = window.open(mypage, myname, settings);
		}
		
	});
	

	new Subscribe("subscribe");
	new Battle("battle");
	new Register("register");
});

