var Site = Class.create();

Site.prototype = {
	
	chooseURL: "<em>Please choose your Account Web Address</em>",
	
	initialize: function()
	{
		Event.observe(window, 'load', this.onPageLoad.bindAsEventListener(this));
	},
	
	onPageLoad: function()
	{
		this.enableEmails();
		if ($(document.body).hasClassName("homepage")) {
		  this.homepage(); 
		}
		
		if ($('signup-form'))
		{
			$('signup-form').observe('submit', function(e) {
				var form = Event.element(e);
				this.signupSubmit(form);
				Event.stop(e);
			}.bindAsEventListener(this));
		}
		
		if ($('account-address'))
		{
			Event.observe('account-id', 'keyup', this.copyAccountID.bindAsEventListener(this));
			Event.observe('account-id', 'change', this.copyAccountID.bindAsEventListener(this));
		}
		
		if ($('accept_terms'))
		{
			$('accept_terms').observe('click', function(e) {
				var element = Event.element(e);
				var bttn = $('submit-button');
				bttn.disabled = !element.checked;
				if (element.checked)
					bttn.removeClassName('is-disabled');
				else
					bttn.addClassName('is-disabled');
			});
		}
		
		if ($('account-id'))
		{
			new Form.Element.DelayedObserver('account-id', .4, this.testAccountCid.bind(this));
			$('account-id').observe('keyup', function(e) {
				var tV = this.value.replace(/[^a-zA-Z0-9]/g, ''); 
				if (tV != this.value) {
					this.value = tV;
				}
			});
		}
		
		if ($('order-windows'))
		{
			this.orderBoxesEvents();
		}
	},
	
	homepage: function() {
	  var win = $$(".windows").first();
	  var online = $$(".online").first();
	  
	  win.observe("mouseover", function() {
	    this.addClassName("hilight");
	    online.removeClassName("hilight");
	  });
	  online.observe("mouseover", function() {
	    this.addClassName("hilight");
	    win.removeClassName("hilight");
	  });
	  
	  new Carousel('testimonials-wrap', $$('#testimonials .testimonial-set'), $$('a.carousel-control', 'a.carousel-jumper'), { 
	    duration: .3,
	    wheel: false
    });
	},
	
	orderBoxesEvents: function()
	{
		$$('#order-windows', '#order-online').each(function(element) {
			element.observe('mouseover', function(e) { element.addClassName('hover'); });
			element.observe('mouseout', function(e) { element.removeClassName('hover'); });
		});
		
		$('order-windows').observe('click', function(e) { location.href = "http://www.dextronet.com/order.php?product=swifttodolist"; });
		$('order-online').observe('click', function(e) { location.href = "http://www.swifttodolist.com/signup"; });
	},
	
	sendingSupportRequest: function()
	{
		$('support-button').hide();
		$('support-sending').show();
	},
	
	supportRequestComplete: function(response)
	{
		var rt = response.responseText;
		
		$('support-button').show();
		$('support-sending').hide();
		
		if (response.status == 403)
		{
			alert(rt);
			return;
		}
		
		$('contact_name').value = "";
		$('contact_email').value = "";
		$('contact_message').value = "";
		
		new Effect.Appear('support-thanks', { duration: .4 });
		new PeriodicalExecuter(function(pe) {
			new Effect.Fade('support-thanks', { duration: .4 });
			pe.stop();
		}, 3);
	},
	
	testAccountCid: function(element, value)
	{
		if (!value)
		{
			$('cid-av').value = "";
			$('test-url-info').update("");
			return;
		}
		
		this.testAccCall(value, function(response) {
			var data = response.responseJSON;
			if (data.success)
			{
				$('cid-av').value = "yes";
				$('test-url-info').update("");
			}
			else
			{
				$('cid-av').value = "no";
				$('test-url-info').update(data.message);
				$('account-address').update(this.chooseURL);
			}
		}.bind(this));
	},
	
	testAccCall: function(value, callback)
	{
		new Ajax.Request('/test_account_name', {
			evalJSON: 'force',
			parameters: { test: value },
			onSuccess: callback
		});
	},
	
	copyAccountID: function(event)
	{
		// todo: kontrola zakazanych jmen
		var elm = Event.element(event);
		var val = elm.value ? ["http://", elm.value, ".swifttodolist.com"].join('') : this.chooseURL;
		$('account-address').update(val);
	},
	
	validateSignup: function()
	{
		if ($F('cid-av') == "no")
		{
			alert('Please choose a different URL. "' + $F('account-id') + '" is not available.');
			return false;
		}
		
		var validators = {
			'account-name': [2, 'Please choose your account name (at least 2 characters).'],
			'admin-first_name': [2, 'Please fill in your name (at least 2 characters).'],
			'admin-last_name': [3, 'Please fill in your name (at least 3 characters).'],
			'admin-username': [2, 'Please choose your username (at least 2 characters).'],
			'admin-password': [4, 'Please choose your password (at least 4 characters).'],
			'account-id': [1, 'Please choose your account web address.']
		};
		
		for (var key in validators)
		{
			if ($F(key).length < validators[key][0])
			{
				alert(validators[key][1]);
				$(key).focus();
				return false;
			}
		}
		
		var r = new RegExp(/^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i);
		if (!r.test($F('admin-email')))
		{
			alert('Please fill in your correct e-mail.');
			$('admin-email').focus();
			return false;
		}
		
		if ($F('admin-password') != $F('admin-password_again'))
		{
			alert('Passwords don\'t match.');
			$('admin-password').focus();
			return false;
		}
		
		return true;
	},
	
	signupSubmit: function(form)
	{
		if (!this.validateSignup())
			return;
		
		$('account-indicator').show(); 
		$('account-buttons').hide();
		
		if ($F('cid-av') != "yes")
		{
			this.testAccCall($F('account-id'), function(response) {
				var data = response.responseJSON;
				if (data.success)
				{
					this.createAccount(form);
				}
				else
				{
					$('cid-av').value = "no";
					$('account-buttons').show();
					$('account-indicator').hide();
					alert('Please choose a different URL. "' + $F('account-id') + '" is not available.');
				}
			}.bind(this));
		}
		else
		{
			this.createAccount(form);
		}
	},
	
	createAccount: function(form)
	{
		new Ajax.Request('/signup/create', { 
			asynchronous: true, 
			evalScripts: false, 
			onComplete: this.accountComplete.bind(this),
			parameters: Form.serialize(form)
		});
	},
	
	accountComplete: function(response)
	{
		if (response.status == 403)
		{
			$('account-buttons').show();
			$('account-indicator').hide();
			alert("There's been an error in creating your account.\n\nPlease try it again later or e-mail us at support@swifttodolist.com.");
			return;
		}
		
		$('account-indicator-text').update("Your account has been created. You are now being redirected to billing form...")
		
		var siteId = response.responseText;
		$('site-id').value = siteId;
		
		$('paypal-form').submit();
	},
	
	redirect: function(href)
	{
		location.href = "http://" + location.host + href;
	},
	
	enableEmails: function()
	{
		$$('span.is-email').each(function(element) {
			var at = / at /;
			var dot = / dot /g;
			var address = element.innerHTML;
			
			address = address.replace(at, "@");
			address = address.replace(dot, ".");
			
			var href = new Element('a', { href: 'mailto:' + address }).update(address);
			
			element.innerHTML = "";
			element.insert(href);
		});
	}
}
