
// outbound links.. assign analytics code
function outboundLink(url)
{
	urchinTracker('/outgoing/' + url);
	window.open(url);
}

// toggle input labels
function toggleInputLabel(textField, blur) {
	if (!blur) {
		if (textField.value == textField.defaultValue) {
			textField.value = '';
		}
	} else if (blur && textField.value == '') {
		textField.value = textField.defaultValue;
	}
}

var box = {};

function initializeOverlay(){
	box = new MultiBox('mb', {
		'descClassName': 'multiBoxDesc',
		'useOverlay': true,
		'showControls': true,
		'colour': '#333',
		'bgImg': '/ri/img/global/gradient_background.png', // for Mac FireFox
		'zIndex': 1050
	});
}

function closeOverlay() {
	box.close();
	if($('workteaser').getElements('a') !== null){
		$('workteaser').getElements('a').setStyle('display','block');
	}
}

window.addEvent('domready', function(){
	$$('h2.sectiontitle').each(function(element, index){
		var src = element.get('html').replace(/[^a-zA-Z0-9\s]/g, '').replace(/\s/g, '_');
		element.erase('html');
		var image = new Element('img',{
			'src': '/ri/img/headers/sectiontitles/' + src + '.gif'
		}).inject(element);
	});
	var ap = new AlphaPng();
	$$('.imglink').addEvents({
		'mouseover': function() {
			if (!this.getAttribute('src').match(/_on\.[a-zA-Z]+$/)) this.setAttribute('src', this.getAttribute('src').replace(/_[^\._]+\.([a-zA-Z]+)$/, '_roll.$1'));
		},
		'mouseout': function() {
			if (!this.getAttribute('src').match(/_on\.[a-zA-Z]+$/)) this.setAttribute('src', this.getAttribute('src').replace(/_[^\._]+\.([a-zA-Z]+)$/, '_off.$1'));
		}
	});
	var limelightForm = new Fx.Morph('limelightdiv', {duration: 500, transition: Fx.Transitions.Sine.easeOut});
	if ($('lnk_subscribe')){
		$('lnk_subscribe').addEvent('click', function(e) {
			e = new Event(e);
			limelightForm.start({
				'height': 175
			});
			e.stop();
		});
		$('closelimelightdiv').addEvent('click', function(e){
			e = new Event(e);
			limelightForm.start({
				'height': 0
			});
			e.stop();
		});
	}
	initializeOverlay();
});

function relative_time(time_value) {
   var parsed_date = Date.parse(time_value);
   var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
   var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);

   if(delta < 60) {
	   return 'less than a minute ago';
   } else if(delta < 120) {
	   return 'about a minute ago';
   } else if(delta < (45*60)) {
	   return (parseInt(delta / 60)).toString() + ' minutes ago';
   } else if(delta < (90*60)) {
		   return 'about an hour ago';
	   } else if(delta < (24*60*60)) {
	   return 'about ' + (parseInt(delta / 3600)).toString() + ' hours ago';
   } else if(delta < (48*60*60)) {
	   return '1 day ago';
   } else {
	   return (parseInt(delta / 86400)).toString() + ' days ago';
   }
}

function handleFlickPhotos(response, id){
	if (response.stat == 'ok'){
		for (var i = 0; i < 9; i++){
			if (response.photos.photo[i]){
				var a = new Element('a', {'title': response.photos.photo[i].title, 'href': 'http://www.flickr.com/photos/resourceinteractive/' + response.photos.photo[i].id + '/'}).inject($(id));
				var img = new Element('img', {'alt': response.photos.photo[i].title, 'src': 'http://farm' + response.photos.photo[i].farm + '.static.flickr.com/' + response.photos.photo[i].server + '/' + response.photos.photo[i].id + '_' + response.photos.photo[i].secret + '_s.jpg'}).inject(a);
			}
		}
		(function(){
			$(id).setStyle('background-image', 'none');
			$$('#' + id + ' a').each(function(el){
				new Fx.Morph(el, {'duration': 'long'}).start({'opacity': [0,1]});
			});
		}).delay(1500);
	}
}

function jsonTwitterApi(response, id){
	var callback = (arguments.length > 2) ? arguments[2] : $empty;
	if(response.results.length > 0){
		var twitterFeed = new Element('ul').inject(id);
		response.results.each(function(tweet, i){
			var postText = tweet.text;
			postText = postText.replace(/\bwww\.\w.\w/ig, 'http://$&');
			postText = postText.replace(/((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g, '<a href="$1">$1</a>');
			postText = postText.replace(/\B@([_a-zA-Z0-9]+)/g, '@<a href="http://twitter.com/$1">$1</a>');
			var tweetHolder = new Element('li');
			var imgLink = new Element('a',{
				'href': 'http://twitter.com/'+tweet.from_user,
				'title': 'Follow ' + tweet.from_user +' on twitter'
			});
			var img = new Element('img', {
				'alt': 'Follow ' + tweet.from_user +' on twitter',
				'src': tweet.profile_image_url
			});
			var textFrom = new Element('p', {
				'html': tweet.source
			});
			var text = new Element('p', {
				'html': postText + ' ' + relative_time(tweet.created_at) + ' via ' + textFrom.get('text')
			});
			var tweeter = new Element('a', {
				'href': 'http://twitter.com/'+tweet.from_user,
				'text': tweet.from_user,
				'title': 'Follow ' + tweet.from_user + ' on twitter'
			}).inject(text,'top');
			tweetHolder.adopt(imgLink.adopt(img));
			tweetHolder.adopt(text).inject(twitterFeed);
		});
		callback.attempt();
	} else $('twitterfeed').set('html', '<li>I\'m sorry, twitter isn\'t talking to us right now :(</li>');
}

var Comment = new Class({
	Implements: [Options, Log],

	defaultOptions: {
		'defaultRange': 5,
		'formFields': {
			'name': {
				'required': true,
				'type': 'line'
			},
			'email': {
				'required': true,
				'type': 'line'
			},
			'website': {
				'required': false,
				'type': 'line'
			},
			'comment': {
				'required': true,
				'type': 'multiline'
			}
		}
	},

	/**
	 * initialize class
	 *
	 * @param object optional options
	 * @return void
	 */
	initialize: function(options){
		// set options
		this.setOptions(this.defaultOptions, options);

		// create container reference
		this.container = $(this.options.container) || null;

		// handle the DWR errors
		dwr.engine.setErrorHandler(function(msg, ex){
			this.log('DWR ERROR');
			this.log(ex);
		}.bind(this));

		this.loadComments();
	},

	/**
	 * load comments into memory
	 */
	loadComments: function(){
		if (this.options.contentId != null){
			try {
				CommentManager.getForContentId(this.options.contentId, 0, 1000, function(data){
					this.log('DWR Comments');
					this.log(data);
					this.displayComments(data);
				}.bind(this));
			}
			catch(e){ this.displayComments(null) }
		}
	},

	/**
	 * get the next range of comments to be shown
	 */
	getNextRange: function(){
		var rest = $(this.options.container).getElements('.inactive');
		var nextRange = [];
		if (rest.length > 0) rest.each(function(el){
			if (nextRange.length < this.options.defaultRange) nextRange[nextRange.length] = el;
		}.bind(this));
		return(nextRange);
	},

	/**
	 * display comments on page
	 */
	displayComments: function(data){
		this.data = data;
		new Element('p', {'class': 'header', 'styles': {'opacity': 0}}).set('html', this.data.length + ' Comments').inject(this.options.container);
		this.data.each(function(comment, idx){
			var c = (idx < this.options.defaultRange) ? 'comment' : 'comment inactive';
			new Element('div', {'class': c, 'styles': {'opacity': 0}}).set('html', '<p>Comment by <a rel="external nofollow" href="' + comment.userURL+ '">' + comment.userName + '</a></p><p>' + comment.text + '</p>').inject(this.options.container);
		}.bind(this));
		if (this.data.length > this.options.defaultRange){
			var a = new Element('a', {'class': 'rangelink', 'href': '#', 'styles': {'opacity': 0}}).set('html', 'show ' + this.getNextRange().length + ' more comments').inject(this.options.container);
			a.addEvent('click', function(){ return(this.displayMoreComments()) }.bind(this));
		}
		$each(['p.header', 'div.comment', 'a.rangelink'], function(set){
			$$('#' + $(this.options.container).get('id') + ' ' + set).each(function(el){
				if (!el.hasClass('inactive')){
					new Fx.Morph(el, {'duration': 'normal'}).start({'display': 'block', 'opacity': 1});
				}
			});
		}, this);
		this.displayForm();
	},

	/**
	 * update controls
	 */
	updateControls: function(){
		$(this.options.container).getElement('p.header').set('html', this.data.length + ' Comments');
		var a = $(this.options.container).getElement('a.rangelink');
		if (a){
			var r = this.getNextRange();
			if (r.length > 0) a.set('html', 'show ' + r.length + ' more comment' + ((r.length > 1) ? 's' : ''));
			else a.destroy();
		}
	},

	/**
	 * display more comments on page
	 */
	displayMoreComments: function(){
		$each(this.getNextRange(), function(el){
			new Fx.Morph(el, {'duration': 'normal', 'onComplete': function(){
				el.removeClass('inactive');
				this.updateControls();
			}.bind(this)}).start({'display': 'block', 'opacity': 1});
		}.bind(this));
		return(false);
	},

	/**
	 * display user comment form
	 */
	displayForm: function(){
		var commentPost = new Element('div', {
			'id': 'postcomments'
		}).inject(this.options.container, 'after');

		var postHead = new Element('p', {
			'class': 'header',
			'id': 'postcomment',
			'text': 'Post a comment'
		});
		commentPost.adopt(postHead);

		var commentForm = new Element('form', {
			'id': 'commentform',
			'events': {
				'submit': function(e){
					e.stop();
					this.saveComment();
				}.bind(this)
			}
		}).inject(commentPost);

		var validate = function(){
			var pass = true;
			$each(this.options.formFields, function(el, key){
				var f = $('comment-' + key);
				if (f.required && f.value == '') pass = false;
			}, this);
			if (pass) $('comment-submit').set('disabled', '').setStyles({'opacity': 1});
			else $('comment-submit').set('disabled', 'disabled').setStyles({'opacity': 0.5});
			return(pass);
		}.bind(this);

		$each(this.options.formFields, function(el, key){
			var label = new Element('label', {
				'for': 'comment-' + key,
				'html': key.capitalize() + (el.required ? ' *' : '')
			});
			switch(el.type){
				case 'line':
					var input = new Element('input', {
						'type': 'text',
						'id': 'comment-' + key,
						'name': 'comment-' + key,
						'class': 'text',
						'events': {
							'change': validate,
							'keyup': validate
						}
					});
					input.required = el.required;
					break;
				case 'multiline':
					var input = new Element('textarea', {
						'type': 'text',
						'rows': 10,
						'cols': 60,
						'id': 'comment-' + key,
						'name': 'comment-' + key,
						'class': 'textarea',
						'events': {
							'change': validate,
							'keyup': validate
						}
					});
					input.required = el.required;
					break;
			}
			var labelWrapper = new Element('p');
			labelWrapper.adopt(label);
			labelWrapper.adopt(input);
			labelWrapper.inject(commentForm, 'bottom');
		}, this);

		var submitButton = new Element('input', {
			'id': 'comment-submit',
			'type': 'image',
			'value': 'Post',
			'tabindex': '5',
			'class': 'button',
			'src': 'http://blog.resource.com/wp-content/themes/resource-20/images/global/submitbutton.gif',
			'alt': 'comment',
			'name': 'submit',
			'disabled': 'disabled',
			'styles': {
				'border': '0',
				'height': '34px',
				'width': '90px',
				'opacity': 0
			}
		}).inject(commentForm);
	},

	/**
	 * save a new comment
	 */
	saveComment: function(){
		this.log('saveComment');
		try {
			CommentManager.addComment(this.options.contentId, $('comment-name').value, $('comment-email').value, $('comment-website').value, $('comment-comment').value, function(data){
				this.log('DWR Post Comment');
				this.log(data);
				this.showSaveStatus(data);
			}.bind(this));
		}
		catch(e){ this.showSaveStatus(null) }
	},

	/**
	 * show save status
	 */
	showSaveStatus: function(data){
		if (data != null){
			$('postcomment').set('text', 'Your comment has been posted.');
			$('commentform').destroy();
			new Element('div', {'class': 'comment inactive', 'styles': {'opacity': 0}}).set('html', '<p>Comment by <a rel="external nofollow" href="' + data.userURL+ '">' + data.userName + '</a></p><p>' + data.text + '</p>').inject(this.options.container);
			this.data[this.data.length] = data;
			this.updateControls();
		} else $('postcomment').set('text', 'Post a comment (form submission failed)');
	}
});


