// beachesTools

//load the blogger tools
google.load('gdata', '1.s');

//load prototype
google.load("prototype", "1.7.0.0");

//load scriptaculous
google.load("scriptaculous", "1.9.0");

var OBuilder = function(type, attributes, children)
{
	var el = new Element(type, attributes);
	if(typeof children == 'string')
	{
		el.update(children);
	}
	else if(Object.isArray(children))
	{
		for(var i = 0, len = children.length; i < len; i++)
		{
			var child = children[i];
			
			//we need to make sure we aren't adding strings directly
			if(typeof child == 'string')
			{
				child = document.createTextNode(child);
			}
			
			if(child)
			{
				el.appendChild(child);
			}
			else if(console && console.warn)
			{
				console.warn('child is null', child);
			}
		}
	}
	
	return el;
}

//creates a sudo random id
var newId = function(opt_prefix)
{	
	return (opt_prefix || '') + Math.ceil(Math.random() * 900000);
}

OTools = {
	removeChildren:function(el)
	{
		$(el).childElements().each(function(el){
			$(el).remove();
		});
	},
	//tells us if the browser supports css3 transitions by returning the accepted rule
	getTransitionRule:function() 
	{		
		//checks to see if we have set it already
		if(!!OTools.transitionRule)
			return OTools.transitionRule;
			
	    var b = document.body || document.documentElement;
	    var s = b.style;
	    var p = 'transition';
	    if(typeof s[p] == 'string') 
	    {
	    	return p;
	    }
	
	    // Tests for vendor specific prop
	    v = ['Moz', 'Webkit', 'Khtml', 'O', 'ms'],
	    p = 'Transition'; //we want uppercase now //p.charAt(0).toUpperCase() + p.substr(1);
	    for(var i=0; i<v.length; i++) 
	    {
	    	if(typeof s[v[i] + p] == 'string') 
	    	{ 
	    		return v[i] + p; 
	    	}
	    }
	    
	    return null;
	}
};
//only does this once
OTools.transitionRule = OTools.getTransitionRule();

//takes a global dot syntax path like: blah.photoManager.functionName:instanceId(param1, … paramN)
var clickHandler = function(exeString)
{
	var exeArray = exeString.split('.');
	var obj = window;
	for(var i = 0, len = exeArray.length - 1; i < len; i ++)
	{
		obj = obj[exeArray[i]];
	}
	
	var idStart = exeArray[len].indexOf(':');
	var funcParamStart = exeArray[len].indexOf('(');
	
	var instanceId = '';
	var nameEnd = funcParamStart;
	if(idStart >= 0)
	{
		nameEnd = idStart;
		instanceId = exeArray[len].substring(idStart + 1, funcParamStart);
	}
	
	var funcName = exeArray[len].substring(0, nameEnd);
	
	var funcParamEnd = exeArray[len].indexOf(')');
	var funcParams = exeArray[len].substring(funcParamStart+1, funcParamEnd);
	funcParams = funcParams.split(',');

	var instance = obj.getInstance(instanceId);

	instance[funcName].apply(instance, funcParams);
}

var onloadHandler = {
	functions:[],
	handleOnLoad:function()
	{
		for(var i = 0, len = onloadHandler.functions.length; i < len; i ++ )
		{
			onloadHandler.functions[i]();
		}
	}
};

//makes a window
onloadHandler.functions.push(function(){

	OWindow = Class.create(
	{
		id:null,//for containing the instance id
		width:0,
		height:0,
		content:null,
		overlay:false,
		className:'',
		initialize:function(options)
		{
			this.id = newId('OW');
			OWindow.registry[this.id] = this;
			
			optons = options || {};
			
			this.width = options.width || 300;
			this.height = options.height || 300;
			this.content = options.content || null;
			this.overlay = options.overlay || true;
			this.className = options.className || '';
			this.build();
		},
		//builds the popover and appends it to the body
		build:function()
		{
			this.overlay = this.overlay?OBuilder('div',{className:'Overlay'}):null;
			
			this.content = this.content || OBuilder('div');
			var inner = OBuilder('div',{className:this.className},[
				this.content
			]);
			$(inner).setStyle({
				width:this.width + 'px',
				height:this.height + 'px'
			});
			
			this.win = OBuilder('div',{className:'OWindow'},[
				inner,
				OBuilder('a',{className:'Close', href:'javascript:clickHandler("OWindow.close:'+this.id+'()")'},[
					OBuilder('span')
				])
			]);
			
			if(!!this.overlay)
			{
				$(this.overlay).hide();
				document.body.appendChild(this.overlay);
				$(this.overlay).appear({to:.5, duration:0.5});
			}
			
			if(!!this.win)
			{
				$(this.win).hide();
				document.body.appendChild(this.win);
				$(this.win).appear({duration:0.5});
			}
			
			this.center();
		},
		//centers the window
		center:function()
		{			
			var dims = document.viewport.getDimensions();
			var winDims = $(this.win).getDimensions();
			
			var x = Math.max((dims.width - winDims.width)/2, 0);
			var y = Math.max((dims.height - winDims.height - 20)/2, 0);
			
			$(this.win).setStyle({
				top:y+'px',
				left:x+'px'
			});
		},
		setContent:function(content)
		{
			if(content)
			{
				$(this.content).replace(content);
				this.content = content;
			}
		},
		close:function()
		{
			this.destroy();
		},
		//destroys the window
		destroy:function()
		{
			if(!!this.overlay)
				$(this.overlay).remove();
				
			if(!!this.win)
				$(this.win).remove();
				
			//remove it out of the instance container so it can be garbage collected
			delete OWindow.registry[this.id];
		}
	});
	
	OWindow.registry = {};
	OWindow.getInstance = function	(id)
	{
		return OWindow.registry[id];
	}
	
	NewsletterSignup = Class.create(
	{
		win:null,
		domNode:null,
		initialize:function()
		{
			NewsletterSignup._instance = this;
			this.show();
		},
		show:function()
		{
			this.domNode = this.buildForm();
			
			this.win = new OWindow({
				width: 460,
				height: 284,
				className:'NewsletterPopup',
				content:this.domNode
			});
		},
		buildForm:function()
		{
			this.signup = OBuilder('div',{className:'SignupForm'},[
				OBuilder('div',{},[
					OBuilder('span', {className:'newsletterIcon'}),
					OBuilder('h4',{},'Read all about it in our monthly'),
					OBuilder('h2',{},'newsletter'),
					OBuilder('p',{},"Subscribe to our monthly newsletter and keep current on Beaches news, including the latest activities, deals, coupons, and promotions! It's the perfect way for us to keep in touch!")
				]),
				OBuilder('div',{id:'EmailFieldset'},[
					OBuilder('label',{},'Your Email Address:'),
					OBuilder('input',{id:'Email'}),
					OBuilder('span',{},'enter an email like name@somewhere.com')
				]),
				OBuilder('div',{className:'submit'},[
					OBuilder('a',{className:'button',href:'javascript:clickHandler("NewsletterSignup.submit()")'},[
						OBuilder('div'),
						'Sign me up!'
					])
				])
			]);
			
			this.sending = OBuilder('div', {className:"MiddleText"}, 'We are submitting your request');
			$(this.sending).setStyle({'display':'none'});
			
			this.goodbye = OBuilder('div', {className:"MiddleText"}, 'Hurrah! It worked! You are now signed up for our monthly newsletter.');
			$(this.goodbye).setStyle({'display':'none'});
			
			this.error = OBuilder('div', {className:"MiddleText"}, [
				"I'm sorry, it didn't work.",
				OBuilder('a',{href:'javascript:clickHandler("NewsletterSignup.tryAgain()")'}, "click here to try again")
			]);
			$(this.error).setStyle({'display':'none'});
			
			return OBuilder('div',{className:'Outter'},[
				this.signup,
				this.sending,
				this.goodbye,
				this.error
			]);
		},
		tryAgain:function()
		{
			$(this.error).fade();
			$(this.signup).appear();
		},
		showSending:function()
		{
			$(this.signup).fade();
			$(this.sending).appear();
		},
		showGoodbye:function()
		{
			$(this.sending).fade();
			$(this.goodbye).appear();
		},
		showError:function()
		{
			$(this.sending).fade();
			$(this.error).appear();
		},
		submit:function()
		{
			if(!this.validate())
				return;
			
			this.showSending();
			var that = this;
			new Ajax.Request('newsletters/signup.php',{
				parameters:{
					Email:$F('Email')
				},
				onComplete:function(transport){
					if(transport.responseText == 'Success')
					{
						NewsletterSignup.getInstance().showGoodbye();
					}
					else
					{
						NewsletterSignup.getInstance().showError();
					}
				}
			});
		},
		validate:function()
		{
			if(!$F('Email').match(/^([a-zA-Z0-9\'_\+\.\-\&])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/))
			{
				$('EmailFieldset').addClassName('error');
				return false;
			}
			
			$('EmailFieldset').removeClassName('error');
			
			return true;
		}
	});
	
	NewsletterSignup._instance = null;
	NewsletterSignup.getInstance = function()
	{
		return NewsletterSignup._instance;
	}

});

google.setOnLoadCallback(onloadHandler.handleOnLoad);
