/**
* Helper method for implementing inheritance.
* @param class parentClassOrObject
* @example myclass.inheritsFrom(ParentClass)
*/
Function.prototype.inheritsFrom = function( parentClassOrObject ){ //helper method for inheritance
	if ( typeof(parentClassOrObject.constructor) == 'function' ) 
	{ 
		//Normal Inheritance 
		this.prototype = new parentClassOrObject;
		this.prototype.constructor = this;
		this.prototype.parent = parentClassOrObject.prototype;
	} 
	else 
	{ 
		//Pure Virtual Inheritance 
		this.prototype = parentClassOrObject;
		this.prototype.constructor = this;
		this.prototype.parent = parentClassOrObject;
	} 
	return this;
}


/**
* This is the base class for ajax forms which reveal themselves upon clicking (or focusing, if text input) on a trigger.  
* @param string wrapper(ex. '#someid') - Wraps the form
* @param string trigger(ex. '#sometrigger') - Triggers the form display
* @var body(jquery Obj) - The document's body element
* @var wrapper(jquery Obj) - The designated form wrapper
* @var error(jquery Obj) - Error message div
* @var success(jquery Obj) - Success message div(must be id of '#' + wrapperid + 'success').  This allows you to put the success message outside of the wrapper
* @var loader(jquery Obj) - Loading gif(must be class of '.ssloader')
* @var form(jquery Obj) - The form element (.ssform)
* @var close(jquery Obj) - Link to close the form (.ssclose)
* @var required(jquery Obj) - Fields that are required (.ssrequired)
* @var optional(jquery Obj) - Fields that are optional
* @var emails(jquery Obj) - Fields that are emails; will be validated (.ssemail)
* @var inputs(jquery Obj) - All inputs
* @var textInputs(jquery Obj) - All text inputs
* @var trig(jquery Obj) - Element that triggers the form
* @var string msg - Error or success message
* @var bool display - Tells whether form is currently displayed/expanded
* @var array initialVals - Stores the inital values of the text fields
*/
function SpiffySignup(wrapper,trigger){
this.body = $('body');
this.wrapper = $(wrapper);
this.error = $(wrapper + ' .sserror');
this.success = $('#'+this.wrapper.attr('id')+'success');
this.loader = $(wrapper + ' .ssloader');
this.form = $(wrapper + ' .ssform');
this.close = $(wrapper + ' .ssclose');
this.required = $(wrapper + ' .ssrequired');
this.optional = $(wrapper + ' :input:not(:hidden)').not(':submit').not('.ssrequired');
this.emails = $(wrapper + ' .ssemail');
this.inputs = this.form.find(':input');
this.textInputs = this.form.find(':text');
this.trig = $(trigger);
this.msg = '';
this.display = 0;
this.initialVals = [];
this.getInitialValues();
this.activateTrigger();
this.activateClose();
this.activateSubmit();
this.activateInputs();
} 
var SS = SpiffySignup;
SS.prototype.activateClose = function() {
	var me = this;
	this.close.bind('click',function(){
		me.closeForm();
	});
}
SS.prototype.getInitialValue = function(obj){
	return this.initialVals[obj.attr('id')];
}
SS.prototype.getInitialValues = function() {
	var me = this;
	$.each(me.textInputs, function() {
			me.initialVals[$(this).attr('id')] = $(this).val();
	});
}
SS.prototype.resetInitialValue = function(obj) {
	var iv = this.getInitialValue(obj);
	obj.val(iv);
}
SS.prototype.clearValue = function(obj) {
	obj.val('');
}
SS.prototype.checkInitialValue = function(obj) {
	var iv = this.getInitialValue(obj);
	if(obj.val() == iv) {
		this.clearValue(obj);
	}
	else if(obj.val() === '') {
		this.resetInitialValue(obj);
	}
}
SS.prototype.setBlur = function(obj) {
	var me = this;
	obj.bind('blur',function() {
		me.checkInitialValue($(this));
	});
}
SS.prototype.setFocus = function(obj) {
	var me = this;
	obj.bind('focus',function() {
		me.checkInitialValue($(this));
	});
}
SS.prototype.activateInputs = function() {
	var me = this;
	$.each(me.textInputs, function() {
	 	if($(this).attr('id')!= me.trig.attr('id')) {
	 		me.setFocus($(this));
	 		me.setBlur($(this));
	 	}
	});
}
SS.prototype.activateTrigger = function() {
	var me = this;
	var bind = 'click';
	if(this.trig.is("INPUT")) {
		bind = 'focus';
		me.setBlur(me.trig);
	}
	this.trig.bind(bind, function() {
			if(bind == 'focus'){
				me.checkInitialValue($(this));
			}
			if(me.display == 0){me.displayForm();}
	});
}
SS.prototype.showLoader = function() {
	this.loader.show();
}
SS.prototype.hideLoader = function() {
	this.loader.hide();
}
SS.prototype.clearMessages = function() {
	this.msg = '';
	this.success.empty();
	this.loader.hide();
	this.error.empty();
}
SS.prototype.clearOptionalFields = function() {
	var me = this;
	$.each(this.optional, function() {
		if($(this).val() === me.getInitialValue($(this))) {
			me.clearValue($(this));
		}
	});
}
SS.prototype.resetOptionalFields = function() {
	var me = this;
	$.each(this.optional, function() {
		if($(this).val() === '') {
			me.resetInitialValue($(this));
		}
	});
}
SS.prototype.resetAllFields = function() {
	var me = this;
	$.each(this.textInputs, function() {
		me.resetInitialValue($(this));
	});
}
SS.prototype.validateEmail = function(email) {
	var myregex = new RegExp('^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.(([0-9]{1,3})|([a-zA-Z]{2,3})|(aero|coop|info|museum|name))$');
	var result = email.match(myregex);
	if(result && result[0] == email){return true;}
	else {return false;}
}
SS.prototype.validateFields = function() {
	var me = this;
	$.each(this.required, function() {
		var iv = me.getInitialValue($(this));
		if($(this).val() === '') {
			me.msg += "Please enter your "+$(this).attr('name')+".<br />";
		}
		else if($(this).val() === iv && iv !== '') {
			me.msg += "Please enter your "+$(this).attr('name')+".<br />";
		}
	});
	$.each(this.emails, function() {
		if(!me.validateEmail($(this).val())){me.msg += "Your email is invalid.<br />";}
	});
	if(this.msg !== '') {
		me.displayErrorMessage();
		return false;
	}
	else {return true;}
}
SS.prototype.disableInputs = function() {
	$.each(this.inputs, function() {
		$(this).attr('disabled','disabled');
	});
}
SS.prototype.enableInputs = function() {
	$.each(this.inputs, function() {
		$(this).removeAttr('disabled');
	});
}
SS.prototype.activateSubmit = function() {
	var me = this;
	this.form.submit(function() {
		me.clearMessages();
		if(!me.validateFields()){me.enableInputs(); return false;}
		me.clearOptionalFields();
		me.showLoader();
		$.ajax({
			type: "POST",
			url: $(this).attr('action'),
			data: me.inputs.serialize(),
			success: function(ret) {
				me.hideLoader();
				me.resetOptionalFields();
				if(ret == '') {
					me.msg = "Thank you for signing up!";
					me.displaySuccessMessage();
					me.resetAllFields();
				}
				else {
					me.msg = 'Your information was not saved!  Please try again.';
					me.displayErrorMessage();	
				}
			},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				me.hideLoader();
				me.msg = 'This request did not work ' + textStatus + errorThrown;
				me.displayErrorMessage();
			}
		});
	});
}
SS.prototype.displaySuccessMessage = function() {
	var me = this;
	var msg = this.parseMessage(this.msg);
	this.success.append(msg);
	this.success.show();
	var closure = function() {
		me.closeForm();	
	}
	setTimeout(closure,1000);
}
SS.prototype.displayErrorMessage = function() {
	var msg = this.parseMessage(this.msg);
	this.error.append(msg);
	this.error.show();
}
SS.prototype.updateDisplayStatus = function() {
	if(this.display === 0){this.display = 1;}
	else {this.display = 0;}
}
SS.prototype.toggleForm = function() {
	this.wrapper.animate({height: 'toggle',opacity: 'toggle'},300,'swing');
	this.updateDisplayStatus();
}
SS.prototype.displayForm = function() {
	this.toggleForm();
}
SS.prototype.closeForm = function() {
	if(this.display === 1){this.toggleForm();}
	this.trig.unbind();
	this.activateTrigger();
}
SS.prototype.addOpaqueLayerDiv = function() {
	$('body').append("<div id='opaquelayer'></div>");
	this.ol = $('#opaquelayer');
	this.ol.css({
		minWidth:'100%',
		minHeight:'100%',
		opacity:'0.5',
		backgroundColor:'#000000',
		zIndex:'100',
		position:'absolute',
		top:'0',
		left:'0',
		display:'none'
	});
}
SS.prototype.toggleOpaqueLayer = function() {
if(this.body.css('overflow') == 'hidden'){this.body.css('overflow','auto')}
else {this.body.css('overflow','hidden')};
this.ol.animate({opacity:'toggle'},300,'swing'); 
}
SS.prototype.parseMessage = function(msg) {
	return msg.replace(/_/,' ');
}


/*************************************/


function LightboxSignup(wrapper,trigger) {
	this.parent.constructor.call(this,wrapper,trigger);
	this.focuselement = $(wrapper + ' .ssfocus');
	this.addOpaqueLayerDiv();
	this.addWrapper();
	this.applyCss();
}
var LS = LightboxSignup;
LS.inheritsFrom(SpiffySignup);
LS.prototype.addWrapper = function() {
	this.wrapper.wrap("<div id='"+this.wrapper.attr('id')+"extrawrapper'></div>");
	this.extrawrapper = $("#"+this.wrapper.attr('id')+"extrawrapper");
	this.success.wrap("<div id='"+this.success.attr('id')+"extrawrapper'></div>");
	this.successwrapper = $("#"+this.success.attr('id')+"extrawrapper");
}
LS.prototype.applyCss = function() {
	this.extrawrapper.css({
		position:'absolute',
		top:'0',
		left:'0',
		width:'100%',
		zIndex:'1000'
	});
	this.wrapper.css({
		position:'relative',
		margin:'0px auto'
	});
	this.successwrapper.css({
		position:'absolute',
		top:'0',
		left:'0',
		width:'100%',
		zIndex:'1000'
	});
	this.success.css({
		margin:'0px auto'
	});
}
LS.prototype.displayForm = function() {
	this.toggleOpaqueLayer();
	this.parent.displayForm.call(this);
	this.focuselement.focus();
}
LS.prototype.closeForm = function() {
	this.parent.closeForm.call(this);
	this.toggleOpaqueLayer();
}
LS.prototype.displaySuccessMessage = function() {
	var me = this;
	this.toggleForm();
	this.success.append(this.msg);
	this.success.animate({opacity:'toggle'},300,'linear');
	var closure = function() {
		me.success.animate({opacity:'toggle'},100,'linear');
		me.closeForm();
	}
	setTimeout(closure,1500);
}



/***************************/


function DropdownSignup(wrapper,trigger) {
	this.parent.constructor.call(this,wrapper,trigger);
	this.additional = $(wrapper + ' .ssadditional');
	this.addOpaqueLayerDiv();
}
var DS = DropdownSignup;
DS.inheritsFrom(SpiffySignup);
DS.prototype.toggleForm = function() {
	this.toggleOpaqueLayer();
	this.additional.animate({height: 'toggle',opacity: 'toggle'},50,'swing');
	if(this.close.css('display') == 'none'){this.close.css('display','block');}
	else{this.close.css('display','none');}
	this.updateDisplayStatus();
}