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];
}

function news_pagination() {
	if ($$('.older').length == 0) return;
	$$('.older a').each(function(el) {
		el.addEvent('click', function(event) {
			var req = new Request.HTML({
				url:this.href,
				evalScripts: false,
				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($('news-list').getElement('.page-navigation'));
						}
						if (node.hasClass('older')) {
							$('news-list').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();
			
			//console.log('event stopping');
			event.stop();
		});
	});
}

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' });
		var tallest = 0;
		
		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));
			
			var shown = this.tabs[i].hasClass('initial');
			this.tabs[i].addClass('initial');
			if (this.tabs[i].getSize().y > tallest) tallest = this.tabs[i].getSize().y;
			if (!shown) this.tabs[i].removeClass('initial');
		}
		
		this.tabs[0].getParent('.mod-content').setStyle('height', tallest+'px');
		
		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);
	}
});

function portfolio_accordion() {
	$$('#portfolio-filters ul').each(function(el) {
		el.iniHeight = el.getSize().y;
	});
	$$('#portfolio-filters h3').each(function(el) {
		el.getElement('a').addEvent('click', function(event) {
			if (this.hasClass('hidden')) {
				this.tween('height', this.iniHeight);
			}
			else {
				this.tween('height', 0);
			}
			this.toggleClass('hidden');
			$(event.target).toggleClass('hidden');
			event.stop();
		}.bind(el.getNext()));
	});
}

function portfolio_show(el) {
	el.removeClass('hidden');
	el.setStyle('display', 'block');
}

function portfolio_hide(el) {
	el.addClass('hidden');
	el.setStyle('display', 'none');
}

function portfolio_update() {
	// Pagination navigation update
	if (portfolio_page_index <= 0) $('portfolio-prev').setStyle('display', 'none');
	else $('portfolio-prev').setStyle('display', 'block');
	if (portfolio_page_index == portfolio_pages.length-1 || portfolio_page_index == -1) $('portfolio-next').setStyle('display', 'none');
	else $('portfolio-next').setStyle('display', 'block');
	var page_msg = "";
	if (portfolio_pages.length > 1) page_msg = "Page " + (portfolio_page_index+1) + " of " + portfolio_pages.length;
	$('portfolio-pages').innerHTML = page_msg;
	
	// Listed companies update
	$$('#portfolio li').each(function(el) {
		if (!el.hasClass('hidden')) portfolio_hide(el);
	});
	portfolio_pages[portfolio_page_index].each(function(el) {
		if (el.hasClass('hidden')) portfolio_show(el);
	});
}

function portfolio_filter() {
	//FILTER
	var companies = $$('#portfolio li');
	var filtered = new Array();	
	$$('#portfolio-filters ul').each(function(el) {
		if (!el.getElement('.all').checked && el.getElements('input:checked').length > 0) {
			el.getElements('input:checked').each(function(i) {
				filtered.combine(companies.filter(function(c) {
					return c.hasClass(i.value);
				}));
			});
			companies = filtered;
			filtered = new Array();
		}
	});
	
	//PAGINATE
	var start = 0;
	var end = 16;
	portfolio_pages = new Array();
	while (start < companies.length) {
		portfolio_pages.push(companies.slice(start, end));
		start+=16;
		end+=16;
	}
	
	portfolio_page_index = portfolio_pages.length == 0 ? -1 : 0;
	
	portfolio_update();
}

function portfolio_page_actions() {
	$('portfolio-prev').getElement('a').addEvent('click', function(event) {
		portfolio_page_index--;
		portfolio_update();
		event.stop();
	});
	$('portfolio-next').getElement('a').addEvent('click', function(event) {
		portfolio_page_index++;
		portfolio_update();
		event.stop();
	});
}

function portfolio_alls() {
	$$('#portfolio-filters .all').each(function(el) {
		el.addEvent('click', function(event) {
			if (this.checked) {
				this.getParent('ul').getElements('input:not(.all)').each(function(i) {
					i.checked = false;
				});
			}
			else {
				this.getParent('ul').getElements('input:not(.all)').each(function(i) {
					i.checked = false;
				});
			}
			
			portfolio_filter();
		}.bind(el))
	});
}

function portfolio_checks() {
	$$('#portfolio-filters input:not(.all)').each(function(el) {
		el.addEvent('click', function(event) {
			var peers = this.getParent('ul').getElements('input:not(.all)');
			var all = true;
			for(var i = 0; i < peers.length && all; i++) {
				all = !peers[i].checked;
			}
			if (all) {
				this.getParent('ul').getElements('.all').each(function(a) {
					a.checked = true;
				});
			}
			else {
				this.getParent('ul').getElements('.all').each(function(a) {
					a.checked = false;
				});
			}
			
			portfolio_filter();
		}.bind(el));
	});
}

function portfolio_selection() {
	$$('#portfolio li a').each(function(el) {
		el.addEvent('click', function(event) {
			event.stop();
			var form = $('filter-form');
			var titles = new Array();
			var urls = new Array();
			portfolio_pages.each(function(page) {
				page.each(function(el) {
					titles.push(el.getElement('a').innerHTML);
					urls.push(el.getElement('a').href);
				});
			});
			/*
			var field = document.createElement('input');
			field.setAttribute('type', 'hidden');
			field.setAttribute('name', 'linkTitles');
			field.setAttribute('value', titles.join(','));
			form.appendChild(field);
			var url = document.createElement('input');
			url.setAttribute('type', 'hidden');
			url.setAttribute('name', 'linkUrls');
			url.setAttribute('value', urls.join(','));
			form.appendChild(url);
			*/
			form.setAttribute('action', $(event.target).href);
			
			form.submit();
		});
	});
}

function portfolio_paramload() {
	var fgup = gup('filters');
	var filters = gup('filters').split(',');
	if (!fgup || fgup == "") { return; }
	else {
		$$('#portfolio-filters input[type=checkbox]').each(function(el) {
			el.checked = false;
		});
	}
	
	for(var i = 0; i < filters.length; i++) {
		$('portfolio-filters').getElement('input[value='+filters[i]+']').checked = true;
	}
	
	$$('#portfolio-filters ul').each(function(el) {
		if (el.getElements('input:not(.all)').filter(function(i) {
			return !i.checked;
		}).length == 0) {
			el.getElement('.all').checked = true;
		}
	})
}

function portfolio_init() {
	var portfolio = $('portfolio');
	if (!portfolio) return;
	
	portfolio_accordion();
	portfolio_alls();
	portfolio_checks();
	portfolio_page_actions();
	portfolio_paramload();
	portfolio_filter();
	portfolio_selection();
}

function center_modal() {
	if (!($('modal-box'))) return;
	
	var modalSize = $('modal-box').getSize();
	var winSize = window.getSize();
	
	var left = winSize.x / 2 - modalSize.x / 2;
	var top = winSize.y / 2 - modalSize.y / 2;
	
	if (left < 0) left = 0;
	if (top < 0) top = 0;
	
	$('modal-box').setStyles({
		'left': left + 'px',
		'top': top + 'px'
	});
}

function create_modal() {
	if (!$('modal-box')) {
		var underlay = new Element('div', {
			'id': 'modal-underlay',
			'html': '&nbsp;',
			'styles': {
				'opacity': 0
			}
		}).inject($('container'));
		var box = new Element('div', {
			'id': 'modal-box'
		}).inject($(document.body));
		var close = new Element('a', {
			'id': 'modal-close',
			'href': '#',
			'html': 'x'
		}).inject(box);
		new Element('div', {
			'id': 'modal-content'
		}).inject(box);
		
		close.addEvent('click', function(event) {
			$('modal-underlay').destroy();
			$('modal-box').destroy();
			event.stop();
		});
		
		underlay.tween('opacity', .5);
	}
	
	$('modal-content').set("html", "<div class='loading'></div>");
}

function setup_modals(selector) {
	$$(selector).each(function(el) {
		el.addEvent('click', function(event) {
			create_modal();
			var req = new Request.HTML({ update:$('modal-content') });
			req.addEvent('onComplete', function() {
				center_modal();
			});
			req.get(this.href)
			event.stop();
		});
	});
	
	window.addEvent('resize', center_modal);
}

function dominit() {
	drfired = true;

	news_pagination();
	portfolio_init();
	setup_modals('.modal-link');
	
	var newsMod = $('wrapper').getElement('#company-detail .aside.right .mod241');	
	if (newsMod) new TabSet(newsMod, newsMod.getElements('.entry'));
}

window.addEvent('domready', function() {
	if (typeof(loadfired) == "undefined") dominit();
});

window.addEvent('load', function() {
	if (typeof(drfired) == "undefined") {
		dominit();
		loadfired = true;
	}
});

