var viralListMachineClass = Class.create({
	
	ajaxLoaderImageUrl:'img/ajax-loader.gif',
	ajaxLoaderEl:null,
	resizePane:null,
	paneEl:null,
	mainDiv:null,
	
	initialize:function()
	{
		this.mainDiv = $('main');
		
		// Signup form
		if ($('signupForm')) {
			$('signupForm').observe('submit', this.checkSignupForm.bindAsEventListener(this));
			
			// Focus
			var formFields = $('signupForm').select('input');
			if (formFields.length > 0) {
				this.highlightFormFields(formFields);
			}
		}
		
		// Autofocus
		var autofocusFields = $$('.autofocus');
		if(autofocusFields.length > 0) {
			autofocusFields[0].focus();
		}
		
		
		if ($('copyLinkImg') != null && Prototype.Browser.IE) {
			$('copyLinkImg').show();
			$('copyLinkImg').observe('click', function(e) {
				$('copyLinkImg').setStyle({ 'cursor':'pointer' });
				$('clipboardText').select();
				var CopiedTxt = document.selection.createRange();
				CopiedTxt.execCommand("Copy");
			});
		}
		
		if (typeof viralListMachineAdminClass != 'undefined') {
			viralListMachineAdmin = new viralListMachineAdminClass(this);
		}
	},
	
	
	
	hideALoader:function()
	{
		this.hidePane(this.hideAjaxLoader.bindAsEventListener(this));
	},
	
	showALoader:function()
	{
		this.showPane(this.showAjaxLoader.bindAsEventListener(this));
	},
	

	
	highlightFormFields:function(formFields)
	{
		formFields.each(function(fld) {
			// Color highlighting on focus
			fld.observe('focus', function(e) { e.element().addClassName('active'); });
			fld.observe('blur',  function(e) { e.element().removeClassName('active'); });
		});
	},
	
	showAjaxLoader:function(yOffset)
	{
		if (yOffset == null) yOffset = 0;
//		yOffset+=this.getVerticalScrollOffset();
		if($(this.ajaxLoaderEl) == null) {
			var loader = new Element('div', { id:'ajaxLoader' });
			$(document.body).appendChild(loader);
			this.ajaxLoaderEl = loader;
			loader.setStyle({
				display:'none',
				border:'1px solid #4d6d77',
				position:'absolute',
				padding:'20px',
				backgroundColor:'white',
				textAlign:'center',
				zIndex:8500
			});
			var img = new Element('img', { src:this.ajaxLoaderImageUrl});
			loader.appendChild(img);
			img.setStyle({ marginBottom:'8px' });
			var txt = new Element('div');
			loader.appendChild(txt);
			txt.setStyle({ color:'#4d6d77', fontWeight:'bold', fontSize:'14px' });
			txt.update('Please wait...');
		}
		this.centerDivInDiv(this.ajaxLoaderEl, -200); //, this.mainDiv, 0, 0);
		
		if (yOffset > 0) {
			this.ajaxLoaderEl.setStyle({ top: yOffset+'px' });
		}
//		alert(this.getVerticalScrollOffset());
		this.ajaxLoaderEl.show();
	},
	
	hideAjaxLoader:function()
	{
		this.ajaxLoaderEl.hide();
	},
	
	centerDivInDiv:function(divToCenter, yOffset)
	{
		var fullDIVSize       = document.viewport.getDimensions();
		var fullDivWidth      = fullDIVSize.width;
		var fullDivHeight     = fullDIVSize.height;
		var divToCenterSize   = divToCenter.getDimensions();
		var divToCenterWidth  = divToCenterSize.width;
		var divToCenterHeight = divToCenterSize.height;
		var divOffsetX        = Math.round((fullDivWidth-divToCenterWidth)/2);
		var divOffsetY        = Math.round((fullDivHeight-divToCenterHeight)/2);
		
		$(divToCenter).setStyle({
			left:(divOffsetX)+'px',
			top:(divOffsetY + yOffset)+'px'
		});
	},
	
	resizePane:function()
	{
		var bodyDimensions = $(document.body).getDimensions();
		var newHeight      = bodyDimensions.height;
		var newWidth       = bodyDimensions.width;
		var viewportHeight = document.viewport.getHeight();

		var viewportHeight2 = $('main').getHeight();

		if (viewportHeight2 > viewportHeight) {
			viewportHeight = viewportHeight2;
		}
		
		if (viewportHeight > newHeight) {
			newHeight = viewportHeight;
		}
		var newDims={ height:newHeight+'px', width:newWidth+'px', top:'0', left:'0' };
		this.paneEl.setStyle(newDims);
	},


	showPane:function(callback)
	{
		Event.observe(window, 'resize', this.resizePane.bindAsEventListener(this));
		//console.log('show pane');
		//var dims = $(document.body).getDimensions();
		var dims = document.viewport.getDimensions();
		//console.log(dims);
		if (this.paneEl == null) {
			
			this.paneEl = new Element('div', {
				id: 'pane'
			});
			$(document.body).appendChild(this.paneEl);
			
			this.paneEl.setStyle({
				display: 'none',
				zIndex: 8000,
				position: 'absolute',
				backgroundColor: '#4d6d77',
				opacity: 0.5
			});
			
			//this.paneEl.observe('click', this.hidePane.bindAsEventListener(this));
		}
		this.resizePane();
		/*
		if(navigator.appVersion.indexOf('MSIE') != -1) {
			var bodyDims = $(document.body).getDimensions();
			this.paneEl.setStyle({
				top:0,
				left:0,
				width:bodyDims.width,
				height:bodyDims.height
			});
		} else {
			Element.clonePosition(this.paneEl, $(document.body));
		}
		*/
		new Effect.Appear(this.paneEl, { to:0.5, duration:0.2, afterFinish:callback});
	},
	
	handleAjaxResult:function(req, callbackSuccess, callbackFailure)
	{
		if (req.status == 200) {
			if(req.responseJSON) {
				var j = req.responseJSON;
				if (j.success == 0) {
					alert(j.message);
					if (callbackFailure != null) {
						callbackFailure(req);
					}
				} else {
					if (callbackSuccess != null) {
						callbackSuccess(j.result);
					}
				}
			} else {
				alert("A server error occured. Please try again later.\nCouldn't parse JSON.");
			}
		} else {
			if (callbackFailure != null) {
				callbackFailure(req);
			}
		}
	},
	
	hidePane:function(callback)
	{
		Event.stopObserving(window, 'resize', this.resizePane.bindAsEventListener(this));
		new Effect.Fade(this.paneEl, { duration:0.2, afterFinish:callback });
	},

	checkSignupForm:function(e)
	{
		var eml = $F('sgnFrmEmail');
		var pwd = $F('sgnFrmPwd');
		var trm = $F('sgnFrmCb');
		
		if (eml == '') {
			$('sgnFrmEmail').focus();
			Event.stop(e);
			alert('Please enter your email address');
		} else if (pwd == '') {
			$('sgnFrmPwd').focus();
			Event.stop(e);
			alert('Please enter a password');
		} else if (!trm) {
			$('sgnFrmCb').focus();
			Event.stop(e);
			alert('Please accept the TERMS AND CONDITIONS');
		} else {
			// Alright, alright, alright! (Remember this from Core Influence? ;)
			// Different formtypes: default, custom, ... (aweber, getresponse etc.)
			var formType;
			var formTypeEl = $('signupForm').down('input[name=autoresponder]');
			if (formTypeEl != null) {
				formType = formTypeEl.getValue();
			} else {
				formType = 'none';
			}
			
			if (formType == 'none') {
				// Submit our form once directly, i.e. allow submission, don't cancel event
				// This actually means that we have nothing to do here :)
			} else {
				// Send form data to us via AJAX first, then submit the form
				// pointing to another domain or service like AWeber etc.
				Event.stop(e);
				this.showALoader();
				new Ajax.Request('signup.php', {
					method:'post',
					parameters:
					{
						e:eml,
						p:pwd,
						src:'ajax'
					},
					
					onComplete:function(req)
					{
						// Empty password, Autoresponder doesn't need to know!
						//this.hideALoader();
						this.handleAjaxResult(req, function() {
							$('sgnFrmPwd').setValue('');
							$('signupForm').submit();
						}, function() {
							this.hideALoader();
							alert("A server error occured. Please try again later.\nGot error code "+req.status+' from server.');
						}.bind(this));
					}.bind(this),
					
					onFailure:function(req)
					{
						this.hideALoader();
						alert('An error occurred. Please try again later.');	
					}
				});
			}
		}
	}
});

var viralListMachine;
Event.observe(window, 'load', function() {
	viralListMachine = new viralListMachineClass();
});

