var Site = {
	// initialisation function
	start : function(){
		Site.behaviour();
	},
	// apply behaviours to elements via CSS selectors
	behaviour : function() {
		$$('#tabcontent').each(function(el,i){
			new ContentSlider(el);
		});
		$$('#news_ticker').each(function(el, i){
			new NewsTicker(el);
		});
	}
};

document.observe('dom:loaded', Site.start);


var NewsTicker = Class.create({

	currItem : 0,

	initialize: function(element){
		this.element = $(element);
		this.options = Object.extend({
			duration: 1,
			interval: 6
		}, arguments[1] || {});
		this.setup();
	},

	setup : function() {
		this.move_logos();
		this.move_title();
		var handler = document.onresize ? document : window;
		Event.observe(handler, "resize", this.move_title.bind(this));
		this.pe = new PeriodicalExecuter(
			function(pe){ this.ticker_action(); }.bind(this),
			this.options.interval
		);
		this.movelogos_pe = new PeriodicalExecuter(
			function(pe){ this.move_logos(); }.bind(this),
			1
		);
	},

	move_title : function(event) {
		var ticker = $$('#news_ticker ul').first().cumulativeOffset(),
			title = $('ticker_title');

		title.setStyle({ left : (ticker.left - title.getWidth()) + 'px' });
	},

	move_logos : function() {
		// move the image to the center of their containers
		$$('#news_ticker li div img').each(function(el, i){
			var marginTop = (el.up().getHeight() - el.getHeight())/2;
			el.setStyle({ marginTop : marginTop + 'px' });
		});
	},

	ticker_action : function() {
		this.currItem++;

		var newTop = 0,
			currPos = parseInt($('ticker_slider').getStyle('top')),
			items = $$('#news_ticker li'),
			numItems = items.length;

		this.currItem = this.currItem < numItems ? this.currItem : 0;
		newTop = this.currItem == 0 ? 0 : currPos - items[this.currItem-1].getHeight() - 5;

		new Effect.Morph('ticker_slider', {
			style : 'top : ' + newTop + 'px',
			duration : this.options.duration
		});
	}

});


var ContentSlider = Class.create({
	initialize: function(element) {
		this.element = $(element); // tab_content
        this.options = Object.extend({
        	transition: Effect.Transitions.sinoidal,
        	duration: 1,
        	defaultOpenBox: 0,
        	timerInterval: 6
        }, arguments[1] || {});
        this.setup();
	},

	setup: function()
	{
		this.element.setStyle({
			'overflow' : 'hidden'
		});

		this.boxes = $$('#' + this.element.id + ' > div > div');
		this.numBoxes = this.boxes.length;

		this.contentWidth = this.element.getWidth();

		this.sliderBox = $$('#' + this.element.id + ' > div').first();
		this.sliderBox.setStyle({'width':((this.contentWidth+200)*this.numBoxes)+120+'px'});

		this.boxes.each(function(el, i)	{
			el.setStyle({'width':this.contentWidth+'px','margin':'0 200px 0 0','float':'left'});
		}.bind(this));

		$$('#tabmenu > ul > li').each(function(el, i){
			el.setStyle({'cursor':'pointer'});
			if (i == this.options.defaultOpenBox) {
				el.addClassName('on');
			}
			el.observe('click', this.slideComponent.bindAsEventListener(this));
		}.bind(this));
	},

	slideComponent : function(e)
	{
		$$('#tabmenu > ul > li').each(function(el, i)
		{
			if(Event.element(e) == el)
			{
				var scrollPos = i * this.contentWidth + (i*200);
				new Effect.Move('sliderBox', { x: -1 * scrollPos, mode: 'absolute' });
				el.addClassName('on');
				this.nextBox = i + 1;
				this.nextBox = this.nextBox > (this.boxes.length -1) ? 0 : this.nextBox;
			} else {
				el.removeClassName('on');
			}
		}.bind(this));
	}

});

function bind(object, method)
{
    var passed = Array.prototype.slice.call(arguments, 2);

    return function()
    {
		var called = Array.prototype.slice.call(arguments, 0)
		var args = called.concat(passed);
        return method.apply(object, args);
    }
}

function Raised()
{
}

Raised.prototype.getNextTimer = function()
{
//(Math.floor(Math.random() * 3) + 1) * 1000
	var raised = (Math.floor(Math.random() * 4) + 1) * 5;
	return raised * this.dollar;
}
Raised.prototype.setup = function(start, finish)
{
	this.start = start;
	this.finish = finish;
	this.expired = Math.floor(new Date().getTime() % (24 * 60 * 60 * 1000) / 1000);
	this.increment = (finish - start) / (24 * 60 * 60);
	this.dollar = (24 * 60 * 60 * 1000) / (finish - start);
	this.base = start + this.increment * this.expired;
	this.startTime = new Date().getTime() - this.expired;
	this.pennies = Math.floor(Math.random() * 9);
}


Raised.prototype.addCommas = function(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

Raised.prototype.updateTime = function()
{
	var currentTime = new Date().getTime();
	var duration = (currentTime - this.startTime) / 1000;
	var money = duration * this.increment + this.base;

	if (Math.floor(Math.random() * 10) == 0)
		this.pennies = Math.floor(Math.random() * 9);

	document.getElementById('header_counter').style.display = 'block';
	document.getElementById('header_counter_value').innerHTML = '$' + this.addCommas(Math.floor(money)) + '.' + this.pennies + '0';

	setTimeout(bind(RAISED, RAISED.updateTime), this.getNextTimer());
}

Raised.prototype.getValues = function()
{
	var _this = this;
	var ajax = new Ajax.Request(baseURL + 'counter/getraised',
	{
		method: 'post',
		onSuccess: function(transport, json)
		{
			result = transport.responseJSON;
			_this.setup(result.start, result.finish);
			_this.updateTime();
		}
	});
}

RAISED = new Raised();
document.observe('dom:loaded', bind(RAISED, RAISED.getValues));
