var HotWebGraphicsClass = new Class.create({
	
	countdownEndDate:null,
	cookieDomain:'',
	cookieCheckUrl:'/ajaxCookieCheck.php',
	
	initialize:function()
	{
		var loc = location.hostname;
		
		this.cookieDomain = loc.replace(/^www\./, '');
		
		// Homepage
		if ($('sgnForm') != null) {
			this.initHomepage();
		}
		
		// ViralForm
		if ($('viralform') != null) {
			this.initViralForm();
		}
		
		// Countdown Timer
		if ($('countdownTimer') != null) {
			this.initCountdownTimer();
		}
		
		// Cookie Check
		if (this.getCookie('cookiecheck') == null) {
			alert('Your browser does not accept cookies.\nPlease enable cookies for this website.');
		}
		
		// CAPTCHA
		if ($('captcha') != null) {
			$('captcha').observe('click', function(e){ Event.stop(e); $('captcha').blur(); $('captcha').down('img').src='/ttt-image.php?'+Math.random(); });
		}

		// Keep alive
		new Ajax.PeriodicalUpdater('keepalive', '/keepAlive.php', { frequency:60 });
	},
	
	initCountdownTimer:function()
	{
		var tmrValue = $('countdownTimer').innerHTML;
		var m = tmrValue.match(/^([0-9]+)\:([0-9]+)\:([0-9]+)$/);
		var cumulatedSeconds = parseInt(m[3]) + (parseInt(m[2])*60) + (parseInt(m[1])*60*60);
		this.countdownEndDate = new Date(new Date().getTime() + cumulatedSeconds*1000);
		
		new PeriodicalExecuter(function(pe) {
//			if (new Date().getTime() )
			var diffSeconds = Math.round((this.countdownEndDate.getTime() - new Date().getTime())/1000);
		//	console.log(diffSeconds);

			if (diffSeconds <= 0) {
				$('countdownTimer').update('!EXPIRED!');				
				pe.stop();
				location.reload();
			} else {
				// Update timer
				var newHrs = Math.floor(diffSeconds/3600);
				var newSeconds = diffSeconds - (newHrs*60*60);
				var newMinutes = Math.floor(newSeconds/60);
				var newSeconds = diffSeconds - newMinutes*60;
				
				if (newHrs < 10) newHrs = '0'+newHrs;
				if (newSeconds < 10) newSeconds = '0'+newSeconds;
				if (newMinutes < 10) newMinutes = '0'+newMinutes;
				$('countdownTimer').update(newHrs+':'+newMinutes+':'+newSeconds);
			}
		}.bind(this), 1);

	},
	
	submitForm:function(e)
	{
		Event.stop(e);
		alert("TOLL!");
	},
	
	initHomepage:function()
	{
		$('sgnForm').down('input').focus();
		//$('sgnForm').observe('submit', this.submitForm.bindAsEventListener(this));
		//$('sbm').observe('click', this.submitForm.bindAsEventListener(this));
		
		$('sbm').observe('click', function(e){
			Event.element(e).blur();
			Event.stop(e);
			var frm = $('sgnForm');
			var name = frm.down('input[name=name]').getValue();
			var email = frm.down('input[name=email]').getValue();
			
			var isLive = frm.hasClassName('live');
			
			if (name.length < 1) {
				alert("Please enter your first name - I won't spam you.");
				frm.down('input[name=name]').focus();
			}
			else 
				if (email.length < 1) {
					alert('I think you forgot to enter your email address.');
					frm.down('input[name=email]').focus();
				}
				else 
					if (!email.match(/^[0-9a-zA-Z\.\_\-]+@[0-9a-zA-Z\.\-]+\.[a-zA-Z]{2,6}$/)) {
						alert("That doesn't look like a valid email address.");
						frm.down('input[name=email]').focus();
					}
					else {
						new Ajax.Request('/signup.php', {
							parameters: {
								n: name,
								e: email,
								live:isLive
							},
							onComplete: function(req){
								var ok = false;
								if (req.responseText == 'ERR') {
									alert("It seems that you entered an invalid email address.");
									frm.down('input[name=email]').focus();
								} else if(req.responseText == 'ASK') {
									if (window.confirm('Is the email address\n'+email+'\n really correct?')) {
										ok = true;
									}
								} else {
									ok = true;
								} 
								
								if (ok == true) {
									top.location.href = 'http://' + location.hostname + '/thanks.php';
								}
							}
						});
					}
		});
		
		/*
		// Test Box!
		var leaveCheckEl = new Element('div', { id:'tricos_leave_checker' });
		$(document.body).appendChild(leaveCheckEl);
		leaveCheckEl.setStyle({
			position:'absolute',
			visibility:'hidden',
			left:0,
			top:0,
			zIndex:999999999,
			opacity:1
		});
		
		var enteredPage = false;
		$(document.body).observe('mouseover', function(e) {
			//console.log(e);
		})
		*/
	},
	
	initViralForm:function()
	{
		var frm = $('viralform');
		frm.observe('submit', this.handleViralFormSubmit.bindAsEventListener(this));
		frm.down('button[name=submit]').observe('click', this.handleViralFormSubmit.bindAsEventListener(this));
		/*
		var nam = frm.down('input[name=uname]').getValue();
		var eml = frm.down('input[name=uemail]').getValue();
		if (nam != '' && eml != '') {
			frm.down('input[name=fname1]').focus();
		} else {
			frm.focusFirstElement();
		}
		*/
	},
	
	handleViralFormSubmit:function(e) 
	{
		Event.stop(e);
		var url = $('viralform').serialize();
//		alert(url);

		// Quick check
		var frm = $('viralform');
		this.unhighlightFields(frm);
		var sbj = frm.down('input[name=subject]');
		var msg = frm.down('textarea');
		//var nam = frm.down('input[name=uname]');
		var eml = $('userEmail').innerHTML;
		var captcha = frm.down('input[name=captcha]');
		var f1n = frm.down('input[name=fname1]');
		var f1e = frm.down('input[name=femail1]');
		var f2n = frm.down('input[name=fname2]');
		var f2e = frm.down('input[name=femail2]');
		var f3n = frm.down('input[name=fname3]');
		var f3e = frm.down('input[name=femail3]');
		var f4n = frm.down('input[name=fname4]');
		var f4e = frm.down('input[name=femail4]');
		var f5n = frm.down('input[name=fname5]');
		var f5e = frm.down('input[name=femail5]');
		
		if (sbj.getValue() == '') {
			this.errorField(sbj);
			alert('The subject must not be empty!');
		} else if (msg.getValue() == '') {
			this.errorField(msg);
			alert('The message must not be empty');
			/*
		} else if (nam.getValue() == '') {
			this.errorField(nam);
			alert('Please enter your name');
		} else if (eml.getValue() == '') {
			this.errorField(eml);
			alert('Please enter your email');
			*/
		} else if (f1n.getValue() == '') {
			this.errorField(f1n);
			alert('Please enter your friends\'s name');
		} else if (f2n.getValue() == '') {
			this.errorField(f2n);
			alert('Please enter your friends\'s name');
		} else if (f3n.getValue() == '') {
			this.errorField(f3n);
			alert('Please enter your friends\'s name');
		/*
		 } else if(!this.validEmail(eml.getValue())) {
			this.errorField(eml);
			alert('Your email address is not valid');
		*/
		} else if(!this.validEmail(f1e.getValue())) {
			this.errorField(f1e);
			alert('Your friend\'s address is not valid');
		} else if(!this.validEmail(f2e.getValue())) {
			this.errorField(f2e);
			alert('Your friend\'s address is not valid');
		} else if(!this.validEmail(f3e.getValue())) {
			this.errorField(f3e);
			alert('Your friend\'s address is not valid');
		} else if(captcha.getValue() == '') {
			this.errorField(captcha);
			alert('Please enter the security code');
		} /*else if(!this.validEmail(f4e.getValue())) {
			this.errorField(f4e);
			alert('Your friend\'s address is not valid');
		} else if(!this.validEmail(f5e.getValue())) {
			this.errorField(f5e);
			alert('Your friend\'s address is not valid');
		}
		*/
		else if (eml == f1e.getValue() || eml == f2e.getValue() || eml == f3e.getValue()) {
			//this.errorField(captcha);
			alert('You entered your own email address as one of your friend\'s addresses.\nPlease don\'t cheat!');
		} else {
			// Everything is ok!
			var oldButtonText = frm.down('button[name=submit]').innerHTML;
			frm.down('button[name=submit]').update("Please wait...");
			frm.down('button[name=submit]').disabled = true;
			new Ajax.Request('/ajaxViral.php', {
				parameters: {
					subject: sbj.getValue(),
					message: msg.getValue(),
					//name:nam.getValue(),
					//email:eml.getValue(),
					friend1name: f1n.getValue(),
					friend1email: f1e.getValue(),
					friend2name: f2n.getValue(),
					friend2email: f2e.getValue(),
					friend3name: f3n.getValue(),
					friend3email: f3e.getValue(),
					friend4name: f4n.getValue(),
					friend4email: f4e.getValue(),
					friend5name: f5n.getValue(),
					friend5email: f5e.getValue(),
					captcha: captcha.getValue()
				}, 
				onComplete: function(req){
					//console.log(req);
					if (req.status != 200) {
						frm.down('button[name=submit]').disabled = false;
						frm.down('button[name=submit]').update(oldButtonText);
						alert("I'm sorry - an error occured.\nPlease try again later.");						
					}
					else {
						frm.down('button[name=submit]').disabled = false;
						frm.down('button[name=submit]').update(oldButtonText);
						if (req.responseText == 'ERRCAPTCHA') {
							$('captcha').down('img').src = '/ttt-image.php?' + Math.random();
							this.errorField(captcha);
							alert('The Security Code was incorrect.');
						} else if (req.responseText == 'ERRDOUBLEFRIENDS') {
							alert('Some of your friends\' addresses are duplicates.\nPlease don\'t cheat!');
						}
						else 
							if (req.responseText == 'ERRFRIENDMAILS') {
								alert('You entered your own email address as one of your friend\'s addresses.\nPlease don\'t cheat!');
							}
							else { 
								top.location.href = 'http://' + location.hostname + '/upgrade.php?from=viral';
							// alert('Done');
							}
					}
				}
.bind(this)
			});
		}
		
	},
	
	validEmail:function(eml)
	{
//		alert(eml);
		return eml.match(/^[0-9a-zA-Z\_\.\-]+@[0-9a-zA-Z\.\-]+\.[a-zA-Z]{2,6}$/);
	},
	
	errorField:function(fld)
	{
		this.highlightField(fld);
		fld.focus();
	},
	
	highlightField:function(fld)
	{
		fld.addClassName('error');
	},
	
	unhighlightFields:function(frm)
	{
		frm.select('input[type=text]').each(function(fld) {
			fld.removeClassName('error');
		});
	},
	
	getCookie:function(name)
	{
        var i=0;
        var suche = name+"=";
        while (i<document.cookie.length){
            if (document.cookie.substring(i, i+suche.length)==suche){
                var ende = document.cookie.indexOf(";", i+suche.length);
                ende = (ende>-1) ? ende : document.cookie.length;
                var cook = document.cookie.substring(i+suche.length, ende);
                return unescape(cook);
            }
            i++;
        }
        return null;
    },

	setCookie:function(name, value, expires, path, domain, secure)
	{
    	expires instanceof Date ? expires = expires.toGMTString() : typeof(expires) == 'number' && (expires = (new Date(+(new Date) + expires * 1e3)).toGMTString());
    	var r = [name + "=" + escape(value)], s, i;
		for(i in s = {expires: expires, path: path, domain: domain}){
			s[i] && r.push(i + "=" + s[i]);
		}
    	return secure && r.push("secure"), document.cookie = r.join(";"), true;
	}

});

var HWG;
Event.observe(window, 'load', function() {
	HWG = new HotWebGraphicsClass();
});
