var global =
{
	i: 0,
	agent: navigator.userAgent.toLowerCase(),
	fetching: true
}

var util =
{
	remove:function(s, t)
	{
		/*
		**  Remove all occurrences of a token in a string
		**    s  string to be processed
		**    t  token to be removed
		**  returns new string
		*/
		i = s.indexOf(t);
		r = '';
		if (i == -1) return s;
		r += s.substring(0,i) + util.remove(s.substring(i + t.length), t);
		return r;
	}
}

var Marvin =
{
	load:function(page)
	{
		if (page.indexOf('/') == 0) page = page.substr(1);

	//	The [load] event on [window] fires after all page images are loaded
	//	The [dom:loaded] event fires immediately after the HTML document is fully loaded, but before images on the page are fully loaded

		Event.observe(window, 'load', function()
		{
			// on the homepage only
			if (page.blank())
			{
				if (global.agent.indexOf('msie') > -1)
				{
					// browse happy
					var browsehappy = new Element('p').update('Marvin recommends a <a href="http://browsehappy.com" rel="external">safe browser</a> for the best browsing experience.');
					var close = new Element('a', { href: "#", 'class': "close", 'title': "Click to close" }).update('<em>X</em>');
					$('browsehappy').insert({ top: browsehappy}).insert(close);
					new Effect.BlindDown($('browsehappy'), { delay: 1.0, duration: 0.5 });
					$$('#warning a.close').each(function(anchor) {
						Event.observe(anchor, 'click', function() {
							new Effect.BlindUp($('browsehappy'), { duration: 0.5 });
						});
					});
				}
			}

			if ($('smstext')) Event.observe($('smstext'), 'click', function(event) {
				Event.stop(event);

				Lightview.show({
					href: '/send-sms',
					rel: 'ajax',
					title: 'Send a text message to Marvin',
					options: {
						autosize: true,
						ajax: {
							onComplete: function() {
								Event.observe($('catwebformform54729'), 'submit', Marvin.submitAjaxSMS);
							}
						}
					}
				});
			});
		});

		document.observe("dom:loaded", function()
		{
			if (!document.getElementsByTagName) return;

			$$('a').each(function(anchor) {
				if (anchor.getAttribute('href') && anchor.getAttribute('rel') == 'external') anchor.target = '_blank';
			}.bind(this));

			$$('ol[class~="feed"]').each(function(item) {
				item.innerHTML = '';
				if (item.hasClassName('twitter')) Marvin.syndicateFeed(item,'http://twitter.com/statuses/user_timeline/15048709.rss');
				if (item.hasClassName('announcements')) Marvin.syndicateFeed(item,'http://help.worldsecuresystems.com/RSSRetrieve.aspx?ID=74&Type=RSS20');
			});

			switch(page)
			{
				case 'tour':
				case 'website':
				case 'ecommerce':
				case 'a-crm':
				case 'email-marketing':
				case 'analytics':
				case 'other-features':
					var pill = new Element('a', { href: "/contact", 'class': "contact" });
					break;
				default:
					var pill = new Element('a', { href: "/tour", 'class': "tour" });
			}

			$('pillbutton').insert(pill);
			$('pillbutton').addClassName('active');

			$$('ol[class^="start_"]').each(function(item) {
				item.writeAttribute({ 'start': util.remove(item.readAttribute('class'), 'start_') });
				item.removeClassName('start_' + util.remove(item.readAttribute('class'), 'start_'));
			});
		});
	},

	submitAjaxSMS:function(event)
	{
		Event.stop(event);

		global.i == 0;
		var reason = '';

		$$('form#catwebformform54729 input').each(function(field) {
			if ((field.identify() == 'FirstName') && field.getValue().blank()) reason += '\r\n- First Name';
			if ((field.identify() == 'LastName') && field.getValue().blank()) reason += '\r\n- Last Name';
			if ((field.identify() == 'EmailAddress') && field.getValue().blank()) reason += '\r\n- Email Address';
		});

		if (reason.blank() && (global.i == 0))
		{
			global.i++;
			Lightview.show({
				href: $('catwebformform54729').readAttribute('action'),
				rel: 'ajax',
				options: {
					title: 'results',
					menubar: false,
					topclose: true,
					autosize: true,
					ajax: {
						parameters: Form.serialize('catwebformform54729')
					}
				}
			});
		}
		else
		{
			if (!reason.blank()) alert('The following fields are required:' + reason);
			if (global.i > 0) alert('Submission already in progress.');
		}
	},

	syndicateFeed:function(e, feedUrl)
	{
		// Make sure the indicator is visible
		$('indicator').show();

		var f = new SimplePie(feedUrl, {

			// Handle a successful response
			onSuccess: function (feed) {

				// Update the list
				// done before the call now
			//	e.innerHTML = '';

				// Store the number of items in a variable so that it processes faster.
				var itemLength = feed.items.length;

				// As long as we have at least one item...
				if (itemLength > 0) {

					// Set the lower boundary for the loop below...
					var itemLengthSpec = itemLength;
					if (e.hasClassName('announcements')) itemLengthLimit = (itemLength-1);
					if (e.hasClassName('twitter')) itemLengthLimit = 2;

					if (itemLengthLimit > itemLength) itemLengthLimit = itemLength;

					// Loop through them and add each entry.
					for (var x = 0; x < itemLengthLimit; x++) {

						// We'll use this to refer to a specific item
						var item = feed.items[x];

						// Let's prepare our HTML
						var li = document.createElement('li');
						li.id = f.getGuid();
						e.appendChild(li);

						// Display it the way we want.
						if (e.hasClassName('announcements'))
						{
							var description = item.description;
							description = util.remove(description, '<a href="http://library.businesscatalyst.com/jobs" target="_blank">Click here</a> to see our example Job Listing site. This examples demonstrates how your website visitors can view current job listings and use the advance search on the left-hand side to search for jobs. You can even allow your website visitors to submit jobs and even edit them later! <br/> <br/>');
							description = description.replace(/<ul>/gi, '<ul class="marker">'); // set a class on UL elements
							description = description.replace(/<ol>/gi, '<ol class="marker">'); // set a class on OL elements
							description = description.replace(/businesscatalyst.com\//gi, 'gotmarvin.com/'); // replace BC domain with GM domain
							description = description.replace(/\/gotmarvin/gi, 'www.gotmarvin'); // always use www prefix on GM domain
							description = description.replace(/http:\/www.gotmarvin.com\//gi, 'http://'); // fix RealEx link
							description = description.replace(/href/gi, 'rel=\"external\" href'); // mark links as external
							description = description.replace(/www.onlinebusinesswiki/gi, 'onlinebusinesswiki'); // always use www prefix on OBW domain
						//	$(li.id).innerHTML = '<a href="' + item.permalink + '"></a>';
							$(li.id).innerHTML = '<h3>' + item.title + '</h3>';
							$(li.id).innerHTML += '<p><span class="date">' + item.date.toLocaleString() + '</span>' + description + '</p>';
						}
						else if (e.hasClassName('twitter'))
						{
							var description = util.remove(item.description, 'gotmarvin: ');
							if (description.indexOf('http') > -1) {
								/*
								1.	find the start character position of the link
								2.	split the string into two sections, the first part everything before the link and the second part the link and beyond
								3.	find the end character position of the link by looking for the first space after the link
								4.	split the link string into two sections, the first part having the link and the second part beyond the link
								5.	add <a> tag surrounding the link string with the link string as the href itself
								6.	join all three strings together to form a new description string
								*/
								var upper = ''; var href = ''; var lower = '';
								global.i = description.indexOf('http');
								upper = description.substr(0,global.i);
								href = description.substring(global.i);
								global.i = href.indexOf(' ');
								if (global.i > -1) // there is text after the link
								{
									lower = href.substr(global.i);
									href = href.substring(0,global.i);
								}
								href = '<a href="' + href + '" rel="external">' + href + '</a>';
								description = upper + href + lower;
							}
						//	$(li.id).innerHTML += '<a href="' + item.permalink + '">';
							$(li.id).innerHTML += description;
						//	$(li.id).innerHTML += '</a>';
						}
					}
				}

				// If there are no items in the feed...
				else {
					// Add a message of nothingness
					var li = document.createElement('li');
					li.appendChild(document.createTextNode('There is no data to display.'));
					e.appendChild(li);
				}

				// Hide the indicator when we're done.
				$('indicator').hide();

				// Remove the no-longer-needed <script> tag from the <head>
				f.cleanup();
			},

			// Handle a failed response
			onFailure: function (feed) {

				// Update the list
				e.innerHTML = '<li>' + feed.error + '</li>';

				// Hide the indicator when we're done.
				$('indicator').hide();
			}
		});
	}
}

var BC =
{
	checkWholeForm17583:function(theForm)
	{
		var why = "";
		if (theForm.CLEmailAddress) why += checkEmail(theForm.CLEmailAddress.value);
		if (why != "")
		{
			alert(why);
			return false;
		}
		theForm.submit();
		return false;
	},

	checkWholeForm18760:function(theForm)
	{
		var why = "";
		if (theForm.FirstName) why += isEmpty(theForm.FirstName.value, "First Name");
		if (theForm.LastName) why += isEmpty(theForm.LastName.value, "Last Name");
		if (theForm.EmailAddress) why += checkEmail(theForm.EmailAddress.value);
		if (why != "")
		{
			alert(why);
			return false;
		}
		if (submitcount18760 == 0)
		{
			submitcount18760++;
			theForm.submit();
			return false;
		}
		else
		{
			alert("Form submission is in progress.");
			return false;
		}
	},

	// replaced by Marvin.submitAjaxForm()
	checkWholeForm54729:function(theForm)
	{
		var why = "";
		if (theForm.FirstName) why += isEmpty(theForm.FirstName.value, "First Name");
		if (theForm.LastName) why += isEmpty(theForm.LastName.value, "Last Name");
		if (theForm.EmailAddress) why += checkEmail(theForm.EmailAddress.value);
		if (why != "")
		{
			alert(why);
			return false;
		}
		if (submitcount54729 == 0)
		{
			submitcount54729++;
			theForm.submit();
			return false;
		}
		else
		{
			alert("Form submission is in progress.");
			return false;
		}
	}
}