/*
################################################################################################################################
# Author: @Dominick
# Call from widgetbank: var widget = new fwSiteSubscribe(${fwuser.id}, {write:true,isSidebar: true,titleText:'$j{titleText}'});
################################################################################################################################
*/
if(!fwuser){ var fwuser = { loggedIn: false }; } 
var siteSubscribe_id = "";

function fwSiteSubscribeClearDefault(el) {
	if ("Enter email address" === el.value) el.value = "";
}

/* ownerID: number, options: object */
function fwSiteSubscribe(ownerID, options) {
	this.type = 'siteSubscribe';
	this.formInput = {};
	
	this.options = {
		width: options.width || '100%',
		titleText: options.titleText || 'Subscribe To My Site',
		buttonText: options.buttonText || 'Subscribe',
		infoLinkText: options.infoLink || 'What\'s this?',
		helpText: options.helpText || 'Subscribing will allow you to receive site updates. Your email address will be kept private.',
		write: options.write || false, /* default false */
		inputName: options.inputName || false, /* default false */
		verifyEmail: options.verifyEmail || false, /* default false */
		
		showLabel: options.showLabel || false,
		showTitle: options.showTitle || false,
		showHelpDiv: options.showHelpDiv || false,
		isSidebar: options.isSidebar || false
	};

	this.ownerID = ownerID;
	this.containerID = siteSubscribe_id = 'siteSubscribe' + Math.round(Math.random() * 100000);
	
	this.prepare();
	if(this.options.write) this.write();
	
}

fwSiteSubscribe.prototype = {
	

	
	/* loads a stylesheet onto the page */
	loadCSS: function(href) {
		var l = document.createElement('link');
		l.rel = 'stylesheet';
		l.type = 'text/css';
		l.href = href;
		(document.getElementsByTagName('head')[0] || document.body).appendChild(l);
	},
	
	createElement:  function(opts) {
		var tmp = document.createElement(opts.type);
		if(typeof opts.html !== 'undefined' && opts.html !== null) tmp.innerHTML = opts.html;
		if(typeof opts.classAtr !== 'undefined' && opts.classAtr !== null) tmp.className = opts.classAtr;
		if(typeof opts.id !== 'undefined' && opts.id !== null) tmp.id = opts.id;
		if(typeof opts.inputType !== 'undefined' && opts.inputType !== null) tmp.type = opts.inputType;
		return tmp;
	},
	
	prepare: function(){

		/* creating the close link element */
		this.hideParentButton = this.createElement({type: 'a', html: 'x', classAtr: 'fwssCloseLink'});
		this.hideParentButton.href ="#";
		this.hideParentButton.setAttribute('onclick','this.parentNode.style.display=\'none\'; return false;');

		/* creating main container */
		this.html = this.createElement({type: 'div', id: this.containerID});
		this.html.style.width = this.options.width;

		/* creating the header div */
		if (this.options.showTitle) {
			this.header = this.createElement({type: 'div', html: this.options.titleText, classAtr: 'fwssHeader'});
			this.header.style.width = this.options.width;
		}

		/* creating the message div */
		this.message = this.createElement({type: 'div', classAtr: 'fwssMessageDiv'});
		this.message.style.display = 'none';

		/* creating the wrapper & form */
		var formWrapper = this.createElement({type: 'div', classAtr: 'fwssSubmitWrapper'});
		this.subForm = document.createElement('form');
		this.subForm.action = 'http://link.members.freewebs.com/s/subscriptions/publicDispatcher';


		var table = document.createElement('table');
		table.setAttribute('style','border-spacing: 0;');

		/* necessary elements to create */
		this.formInput.name = this.createElement({type: 'input', inputType: 'text', classAtr: 'fwssTextInput'});
		this.formInput.email = this.createElement({type: 'input', id: 'subscribeSite_email', inputType: 'text', classAtr: 'fwssTextInput'});
		this.formInput.email.value = "Enter email address";
		this.formInput.email.setAttribute('name','email');
		this.formInput.email.setAttribute('onfocus','fwSiteSubscribeClearDefault(this)');
		
		this.formInput.verifyEmail = this.createElement({type: 'input', inputType: 'text', classAtr: 'fwssTextInput'});
		this.formInput.submit = this.createElement({type: 'input', inputType: 'submit', classAtr: 'fwssSubmit fw-button fw-button-big'});
		this.formInput.submit.setAttribute('value',this.options.buttonText);

		/*================= Generic =================*/
		if (!this.options.isSidebar){
			/* Place for name */
			if(this.options.inputName) {
				var tr = document.createElement('tr');
				var td_name = this.createElement({type: 'td', html: 'name: '});
				var td_input = document.createElement('td');

				td_input.appendChild(this.formInput.name);
				tr.appendChild(td_name);
				tr.appendChild(td_input);
				table.appendChild(tr);
			}

			/* Place for email */
				var tr = document.createElement('tr');
				var td_name = this.createElement({type: 'td', html: 'email:'});
				var td_input = document.createElement('td');

				td_input.appendChild(this.formInput.email);
				tr.appendChild(td_name);
				tr.appendChild(td_input);
				table.appendChild(tr);

			/* Place for verify email */
			if(this.options.verifyEmail) {
				var tr = document.createElement('tr');
				var td_name = this.createElement({type: 'td', html: 'verify email: '});
				var td_input = document.createElement('td');

				td_input.appendChild(this.formInput.verifyEmail);
				tr.appendChild(td_name);
				tr.appendChild(td_input);
				table.appendChild(tr);
			}

			/* Submit Button */
			var tr = document.createElement('tr');
			var td_input = document.createElement('td');
			td_input.setAttribute('colspan','2');
			td_input.appendChild(this.formInput.submit);

			if(this.options.showHelpDiv){
				this.helpLink = this.createElement({type: 'a', classAtr: 'fwssHelpLink', html: this.options.infoLinkText});
				this.helpLink.setAttribute('href', '#');
				td_input.appendChild(this.helpLink);
			}
			tr.appendChild(td_input);
			table.appendChild(tr);

			/* help div */
			if(this.options.showHelpDiv) {
				this.helpDiv = this.createElement({type: 'div', classAtr: 'fwssHelpDiv fw-secondary', html: this.options.helpText});
				this.helpDiv.appendChild(this.hideParentButton);
				this.helpDiv.style.display = 'none';
			}
		} else {
		/*================= Sidebar =================*/
			this.formInput.submit.className = "fwssSubmit fw-button fw-button-small";
			this.formInput.email.style.height = "13px";
			
			var tbody = document.createElement('tbody');
			var tr = document.createElement('tr');
			var td_input = document.createElement('td');
			var td_submit = document.createElement('td');

			var sidebarWidth = 260;
			if (document.getElementById("fw-sidebar") !== null) {
				sidebarWidth = document.getElementById("fw-sidebar").scrollWidth;
			}
			var tbWidth = sidebarWidth - 15;
			tbWidth = (tbWidth < 260 ? tbWidth : 260);
			
			if (sidebarWidth > 260){
				table.style.width = tbWidth + "px";
				td_submit.style.width = "85px";
				td_input.style.width = tbWidth - 85 + "px";

				this.formInput.email.style.width = tbWidth - 85 -10 + "px";

				td_input.appendChild(this.formInput.email);
				td_submit.appendChild(this.formInput.submit);
				tr.appendChild(td_input);
				tr.appendChild(td_submit);
				tbody.appendChild(tr);
				table.appendChild(tbody);
			} else {
				if(sidebarWidth > 180){
					this.formInput.email.style.width = 170 + "px";
				} else {
					this.formInput.email.style.width = 100 + "%";
				}
				this.formInput.submit.style.margin = "4px 0 0 0";
				
				td_input.appendChild(this.formInput.email);
				td_input.appendChild(this.formInput.submit);
				tr.appendChild(td_input);
				tbody.appendChild(tr);
				table.appendChild(tbody);
			}

		}


		/* appending it all together */
		this.subForm.appendChild(table);
		formWrapper.appendChild(this.subForm);
		if(this.options.showTitle) this.html.appendChild(this.header);
		this.html.appendChild(this.message);
		this.html.appendChild(formWrapper);
		if(this.options.showHelpDiv) this.html.appendChild(this.helpDiv);

		this.loadCSS('http://images.freewebs.com/Styles/fwSiteSubscribe.css');
	},
	
	write: function(){

		var id = "container-" + this.containerID;
		document.write('<div id="' + id + '"></div>');
		document.getElementById(id).appendChild(this.html);	
		this.activate();
	},
	
	getValidateErrors: function(){
		if(this.options.inputName){
			if(!this.formInput.name.value){
				return 'Please enter your name.';
			}
		}
		if(!this.formInput.email.value){
			return 'Please enter your email address.';
		}
		if(!(this.formInput.email.value+'').match(/[^@]+[@][^@.]+[.].+/i)){
			return 'Please enter a valid email address.';
		}
		if(this.options.verifyEmail) {
			if(this.formInput.email.value != this.email2.value){
				return 'Email addresses do not match.';
			}
		}
		return false;
	},
	
	setMessage: function(msg){
		this.message.innerHTML = msg;
		if(!this.options.isSidebar) this.message.appendChild(this.hideParentButton);
		this.message.style.display = 'block';
	},
	
	activate: function(){

		if(!this.options.inputName) this.formInput.name.value = "Site Subscriber";
		if(!this.options.verifyEmail) this.formInput.verifyEmail = this.formInput.email;

		var that = this;

		if (this.options.showHelpDiv){
			this.helpLink.onclick = function(){
				that.helpDiv.style.display = that.helpDiv.style.display=='block' ? 'none' : 'block';
				return false;
			}
		}

		this.subForm.onsubmit = function(){

			if(this.isProcessing) return false;
			var err = that.getValidateErrors();
			if(err){ 
				that.setMessage(err);
				return false;
			}

			this.isProcessing = true;

			that.dispatch('invite', 'crash', {
				callback: 'submitButtonCallback',
				data: {
					name: encodeURIComponent(that.formInput.name.value),
					email: encodeURIComponent(that.formInput.email.value),
					email2: encodeURIComponent(that.formInput.verifyEmail.value)
				}
			});
			return false;
		}
	},
	
	dispatch: function(section, action, options){

		options.statusMsg = 'Please Wait...';
		options.data.ownerID = this.ownerID;
		options.data.section = section;
		options.data.action = action;
		options.data.callback = options.callback;
		this.setMessage(options.statusMsg);

		this.jjax.req('http://link.members.freewebs.com/s/subscriptions/publicDispatcher', {
			appendTo: this.html,
			postBody: options.data
		});
		return false;
	},
	
	jjax: {
		req: function(url, options) {
			this.url = '';
			this.options = options;
			for(var i in this.options.postBody) this.url +=	((this.url=='') ? '' : '&') + i + '=' + this.options.postBody[i];
			this.url = url + (this.options.postBody ? '?' : '') + this.url;
			this.send();
		},
		send: function() {
			var script = document.createElement('script');
			script.src = this.url;
			script.type = "text/javascript";
			this.options.appendTo ? this.options.appendTo.appendChild(script) : document.body.appendChild(script);
		}
	}
	
}

function makeSafe(fs, encodeSpaces) {
	//  This is for when fs is the value of an input.  i.e.  value="fs".  Similar perhaps to StringUtil.editHtml()
	if (encodeSpaces){
		fs = fs.replace(/ /g, "&nbsp;");
	} 
	fs = fs.replace(/</g, "&lt;");
	fs = fs.replace(/>/g, "&gt;");
	fs = fs.replace(/"/g, "&quot;");
	fs = fs.replace(/\n/g, "<BR>");
	return fs;
}

function submitButtonCallback(response){
	if(response.error){
		alert(response.errorMsg);
		return false;
	}

	document.getElementById(siteSubscribe_id).innerHTML = '\
	<table class="fwssFinished"><tr><td>\
		<div class="fwssFinishedTitle">Thank you!</div>\
		<div>To complete the registration process, please click the link in the email we just sent to\
		 <b>'+ makeSafe(document.getElementById('subscribeSite_email').value,true) +'</b>.</div>\
	</td></tr></table>\
	';
}