if (typeof window["console"] == 'undefined') { var console = {}; console.log = function () {}; console.dir = function () {}; console.warn = function () {}; }

/* Netlobo Get User Parameter Function */
function gup( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}

/**********
Begin Valerio's Mootools Scrollbar Plugin
[http://mootools.net/uploads/scrollbar/]
**********/
var ScrollBar = new Class({

	Implements: [Events, Options],

	options: {
		maxThumbSize: 10,
		wheel: 8
	},

	initialize: function(content, track, thumb, options){
		this.setOptions(options);

		this.content = $(content);
		this.track = $(track);
		this.thumb = $(thumb);

		this.bound = {
			'start': this.start.bind(this),
			'end': this.end.bind(this),
			'drag': this.drag.bind(this),
			'wheel': this.wheel.bind(this),
			'page': this.page.bind(this)
		};

		this.position = {};
		this.mouse = {};
		this.update();
		this.attach();
	},

	update: function(){

		this.contentSize = this.content.offsetHeight;
		this.contentScrollSize = this.content.scrollHeight;
		
		if (this.contentSize + 3 >= this.contentScrollSize) this.track.getParent().setStyle('display', 'none');
		
		this.trackSize = this.track.offsetHeight;

		this.contentRatio = this.contentSize / this.contentScrollSize;

		this.thumbSize = (this.trackSize * this.contentRatio).limit(this.options.maxThumbSize, this.trackSize);

		this.scrollRatio = this.contentScrollSize / this.trackSize;

		this.thumb.setStyle('height', this.thumbSize);

		this.updateThumbFromContentScroll();
		this.updateContentFromThumbPosition();
	},

	updateContentFromThumbPosition: function(){
		this.content.scrollTop = this.position.now * this.scrollRatio;
	},

	updateThumbFromContentScroll: function(){
		this.position.now = (this.content.scrollTop / this.scrollRatio).limit(0, (this.trackSize - this.thumbSize));
		this.thumb.setStyle('top', this.position.now);
	},

	attach: function(){
		this.thumb.addEvent('mousedown', this.bound.start);
		if (this.options.wheel) this.content.addEvent('mousewheel', this.bound.wheel);
		this.track.addEvent('mouseup', this.bound.page);
	},

	wheel: function(event){
		this.content.scrollTop -= event.wheel * this.options.wheel;
		this.updateThumbFromContentScroll();
		event.stop();
	},

	page: function(event){
		if (event.page.y > this.thumb.getPosition().y) this.content.scrollTop += this.content.offsetHeight;
		else this.content.scrollTop -= this.content.offsetHeight;
		this.updateThumbFromContentScroll();
		event.stop();
	},

	start: function(event){
		this.mouse.start = event.page.y;
		this.position.start = this.thumb.getStyle('top').toInt();
		document.addEvent('mousemove', this.bound.drag);
		document.addEvent('mouseup', this.bound.end);
		this.thumb.addEvent('mouseup', this.bound.end);
		event.stop();
	},

	end: function(event){
		document.removeEvent('mousemove', this.bound.drag);
		document.removeEvent('mouseup', this.bound.end);
		this.thumb.removeEvent('mouseup', this.bound.end);
		event.stop();
	},

	drag: function(event){
		this.mouse.now = event.page.y;
		this.position.now = (this.position.start + (this.mouse.now - this.mouse.start)).limit(0, (this.trackSize - this.thumbSize));
		this.updateContentFromThumbPosition();
		this.updateThumbFromContentScroll();
		event.stop();
	}

});
/* End Valerio's Mootools Scrollbar Plugin */

var TabSet = new Class({
	tabs: [],
	tabLinks: [],
	active: null,
	
	initialize: function(navParent, tabClass, delay) {
		this.tabs = $$(tabClass);
		if (this.tabs.length < 2) return;

		var ul = new Element('ul', { 'class': 'tab-nav' });
		
		for(var i = 0; i < this.tabs.length; i++) {
			var li = new Element('li');
			var a = new Element('a', {
				'href': '#',
				'html': '*'
			});
			this.tabLinks.push(a);
			if (this.tabs[i].hasClass('initial')) {
				a.addClass('selected');
				this.active = this.tabs[i];
			}
			a.injectInside(li.injectInside(ul));
		}
		
		this.tabLinks.each(function(el, ndx) {
			el.addEvent('click', function(event) {
				$clear(this.pclear);
				this.tabLinks.each(function(lin) { lin.removeClass('selected'); });
				this.tabLinks[ndx].addClass('selected');
				if (this.tabs[ndx] != this.active) {
					var fadeOut = new Fx.Tween(this.active, {
						link: 'cancel',
						transition: 'quad:in',
						duration: '400',
						property: 'opacity'
					});
					
					fadeOut.addEvent('onComplete', function() {
						this.active.setStyle('display', 'none');
						this.tabs[ndx].set('opacity', '0');
						this.tabs[ndx].setStyle('display', 'block');
						var fadeIn = new Fx.Tween(this.tabs[ndx], {
							link: 'cancel',
							transition: 'quad:out',
							duration: '400',
							property: 'opacity'
						}).start(0, 1);
						this.active = this.tabs[ndx];
					}.bind(this));
					
					fadeOut.start(0);
				}
				return false;
			}.bind(this));
		}, this);
		
		ul.injectInside(navParent);
		if (delay) this.startPeriodical.delay(5000, this);
		else this.pclear = this.cycle.periodical(10000, this);
	},
	
	startPeriodical: function() {
		this.pclear = this.cycle.periodical(10000, this);
	},
	
	cycle: function() {
		var i;
		for (i = 0; this.tabs[i] != this.active; i++);
		if (i == this.tabs.length - 1) i = 0; else i++;
		
		this.tabLinks.each(function(lin) { lin.removeClass('selected'); });
		this.tabLinks[i].addClass('selected');
		var fadeOut = new Fx.Tween(this.active, {
			link: 'cancel',
			transition: 'quad:in',
			duration: '400',
			property: 'opacity'
		});
		
		fadeOut.addEvent('onComplete', function() {
			this.active.setStyle('display', 'none');
			this.tabs[i].set('opacity', '0');
			this.tabs[i].setStyle('display', 'block');
			var fadeIn = new Fx.Tween(this.tabs[i], {
				link: 'cancel',
				transition: 'quad:out',
				duration: '400',
				property: 'opacity'
			}).start(0, 1);
			this.active = this.tabs[i];
		}.bind(this));
		
		fadeOut.start(0);
	}
});

var notable_autoselected = false;

function investment_init() {
	if (!$('investment-viewer')) return;
	inv_sector = gup('sector');
	inv_location = gup('location');
	inv_partner = gup('partner');
	inv_page = gup('page');
	
	$$('.two-col .lcol h2').addEvent('click', function(event) {
		$$('.filter-nav').addClass('contracted');
		this.getNext().removeClass('contracted');
		$$('.two-col .lcol h2.expanded').removeClass('expanded');
		this.addClass('expanded');
		this.getNext().getElement('a').fireEvent('click');
		investment_query(investment_endpoint);
	});
	
	$$('.filter-nav a').addEvent('click', function(event) {
		inv_page = 1;
		if (this.href.contains('sector')) {
			inv_sector = this.href.substring(this.href.lastIndexOf('/') + 1);
			inv_location = inv_partner = 'all';
		}
		else if (this.href.contains('location')) {
			inv_location = this.href.substring(this.href.lastIndexOf('/') + 1);
			inv_sector = inv_partner = 'all';
		}
		else if (this.href.contains('partner')) {
			inv_partner = this.href.substring(this.href.lastIndexOf('/') + 1);
			inv_sector = inv_location = 'all';
		}
		
		$$('.filter-nav a.selected').removeClass('selected');
		if (inv_sector == 7 && !$('notable-investments').checked) {
			$('notable-investments').checked = true;
			notable_autoselected = true;
		}
		else if (notable_autoselected && inv_sector != 7) {
			$('notable-investments').checked = false;
			notable_autoselected = false;
		}
		this.addClass('selected');
		investment_query(investment_endpoint);
		return false;
	});
	
	$$('.filter-page a').addEvent('click', function(event) {
		inv_page = this.href.contains('page') ? this.href.substring(this.href.lastIndexOf('/') + 1) : 1;
		this.getParent().getParent().getElement('a.selected').removeClass('selected');
		this.addClass('selected');
		investment_query(investment_endpoint);
		return false;
	});
	$$('.filter-box').addEvent('click', function(event) {
		inv_page = 1;
		if (!$('current-investments').checked && !$('notable-investments').checked) {
			$('current-investments').checked = true;
			$('notable-investments').checked = true;
		}
		investment_query(investment_endpoint);
		return true;
	});
	// check if sector link
	if (window.location.href.contains('sector')) {
		inv_sector = window.location.href.substring(window.location.href.lastIndexOf('/') + 1);
	}
}
function investment_pagination(page,totalPages,totalRows) {
	// set total records 
	$('investment-count').value = totalRows;
	// if no records hide pagination
	if (!totalRows) {
		$('investment-viewer').getElement('.pagination').setStyle('display','none');
		return;
	}
	// set `Page x of y`
	$('investment-page-range').innerHTML = 'Page ' + page + ' of ' + totalPages;
	// reset page links
	var ul = $('investment-viewer').getElement('.filter-page');
	while(ul.childNodes[0]) {
		ul.removeChild(ul.childNodes[0]);
	}
	// previous
	if (page > 1) {
		var li = new Element('li');
		var a = new Element('a', {
			'href': '/page/' + ( page - 1),
			'html': 'Prev',
			'class': 'prev'
		});
		a.injectInside(li.injectInside(ul));
	}
	// pages
	var pageStart;
	var pageEnd;
	if (page > 3) {
		if ( (page + 2) > totalPages ) {
			pageEnd = totalPages;
			pageStart = (pageEnd - 5) < 1 ? 1 : pageEnd - 4;
		} else {
			pageEnd = page + 2;
			pageStart = ((pageEnd - 5) < 1) ? 1 : pageEnd - 4;
		}
	} else {
		pageStart = 1;
		pageEnd = totalPages > 5 ? 5 : totalPages;
	}
	for(var i = pageStart; i <= pageEnd; i++) {
		var li = new Element('li');
		var a = new Element('a', {
			'href': '/page/' + i,
			'html': i
		});
		if (i == page) {
			a.addClass('selected');
		}
		a.injectInside(li.injectInside(ul));
	}
	// previous
	if (page < totalPages) {
		var li = new Element('li');
		var a = new Element('a', {
			'href': '/page/' + ( page + 1),
			'html': 'Next',
			'class': 'next'
		});
		a.injectInside(li.injectInside(ul));
	}
	$('investment-viewer').getElement('.pagination').setStyle('display','');
}
function investment_query(endpoint) {
	$('investment-chips').setStyle('background', 'url(../images/ajax-loader.gif) 300px center no-repeat');
	$$('.chip').set('opacity', 0);
	
	var req = new Request.JSON({
		url:endpoint,
		onSuccess: function(responseJSON, responseText) {
			$('investment-chips').setStyle('background', 'none');
			$('investment-chips').set('text', '');
			$('investment-chips').innerHTML = responseJSON.chips;
			investment_pagination(responseJSON.page,responseJSON.totalPages,responseJSON.totalRows);
			$$('.filter-page a').addEvent('click', function(event) {
				inv_page = this.href.contains('page') ? this.href.substring(this.href.lastIndexOf('/') + 1) : 1;
				this.getParent().getParent().getElement('a.selected').removeClass('selected');
				this.addClass('selected');
				investment_query(endpoint);
				return false;
			});
		},
		onFailure: function() {
			/* Put original elements back, maybe display a message */
			$('investment-chips').setStyle('background', 'none');
			$$('.chip').set('opacity', 1);
		}
	}).get({
		'sector': inv_sector,
		'location': inv_location,
		'partner': inv_partner,
		'current': $('current-investments').checked ? 1 : 0,
		'notable': $('notable-investments').checked ? 1 : 0,
		'page': inv_page
	});
}
function news_pagination() {
	if ($$('.older').length == 0) return;
	$$('.older a').each(function(el) {
		el.addEvent('click', function() {
			var req = new Request.HTML({ url:this.href,
				onSuccess: function(tree, elems, html, js) {
					var lastpage = true;
					for (var i = 0; i < elems.length; i++) {
						var node = elems[i];
						if (node.hasClass('entry')) node.injectBefore($('content').getElement('.page-navigation'));
						if (node.hasClass('older')) {
							$('content').getElement('.older a').setAttribute('href', node.getElement('a').getAttribute('href'));
							lastpage = false;
						}
					}
					lastpage ? $$('.older').setStyle('display', 'none') : $$('.older').setStyle('display', 'block');
				},
				
				onFailure: function() {
					location.href = this.href;
				}
			}).get();
			return false;
		});
	});
}
function pullquotes() {
	 var rounded_divs = $$('.pullquote');
	 for (var i = 0; i < rounded_divs.length; i++) {
	   var original = rounded_divs[i];
	   original.removeClass('pullquote');
	   var tr = document.createElement('div');
	   tr.className = 'pullquote';
	   original.parentNode.replaceChild(tr, original);
	   var tl = document.createElement('div');
	   var br = document.createElement('div');
	   tr.appendChild(tl);
	   tl.appendChild(br);
	   br.appendChild(original);
	 } 
}

function dominit() {
	drfired = true;
	JSHTML.parse();
	$$('.spotlight').each(function(el) {
		el.setStyle('display', 'block');
		if (el.getSize().y > $('investment-spotlight').getSize().y) {
			new Element('div', {'class':'scroll-content'}).adopt(el.getChildren()).inject(el);
			$('recent-news').getElement('.track-wrap').clone().inject(el);
			new ScrollBar(el.getElement('.scroll-content'), el.getElement('.track'), el.getElement('.thumb'));
		}
		if (!el.hasClass('initial')) el.setStyle('display', 'none');
	});
	if ($('investment-spotlight')) new TabSet($('investment-spotlight'), '.spotlight', true);
	if ($('team-spotlight')) new TabSet($('team-spotlight'), '.profile', 5000);
	if ($('ceo-quotes')) new TabSet($('ceo-quotes'), '.ceo-quote');
	if ($('successes')) new TabSet($('successes'), '.frame');
	if ($('filter-submit')) $('filter-submit').setStyle('display', 'none');
	pullquotes();
	$('searchinput').addEvent('focus', function(event) {
		if (this.get('value') == 'Search') this.set('value', '');
	});
	$('searchinput').addEvent('blur', function(event) {
		if (this.get('value') == '') this.set('value', 'Search');
	});
	
	news_pagination();
}

window.addEvent('domready', function() {
	if (typeof(loadfired) == "undefined") dominit();
});

window.addEvent('load', function() {
	if (typeof(drfired) == "undefined") {
		dominit();
		loadfired = true;
	}
	var rnScroll = $('recent-news');
	var riScroll = $('recent-investments');
	var relnScroll = $('related-news');
	var invScroll = $('investments');
	var spotScroll = $('list-spotlight');

	if (rnScroll) new ScrollBar(rnScroll.getElement('dl'), rnScroll.getElement('.track'), rnScroll.getElement('.thumb'));
	if (riScroll) new ScrollBar(riScroll.getElement('ul'), riScroll.getElement('.track'), riScroll.getElement('.thumb'));
	if (relnScroll) new ScrollBar(relnScroll.getElement('dl'), relnScroll.getElement('.track'), relnScroll.getElement('.thumb'));
	if (invScroll) new ScrollBar($('investment-container'), invScroll.getElement('.track'), invScroll.getElement('.thumb'));
	if (spotScroll) new ScrollBar(spotScroll.getElement('ul'), spotScroll.getElement('.track'), spotScroll.getElement('.thumb'));
});
