// Updater for number of posts
// Note: Is only updated on true success.
var counter = new Ajax.PeriodicalUpdater(
	{success: 'debatcounter_holder'},
	'/elements/html/common/text_debatcount.shtml',
	{
		asynchronous: true,
		method: 'get',
		frequency: 90
	}
);

var tabs;		// Temp container for various tab arrays


function contestRotation(id, contests) {
	this.show		= crShow;
	this.hide		= crHide;
	this.load		= crLoad;
	
	this._id		= id;
	this._selected	= -1;
	this._contests	= contests;
	
	$(this._id).style.display = 'none';
				
	if (this._contests.length >= 1)
		this.load();
}

function crShow() {
	new Effect.Appear( $(this._id) );
}

function crHide() {
	new Effect.Fade( $(this._id), { to: 0.01 } );
}

function crLoad() {
	var rand = this._selected;
	var c = 0;
	
	while (rand == this._selected) {
		rand = Math.floor(Math.random() * this._contests.length);
		c++;
		if (c >= 10)
			break;
	}
	this._selected = rand;
	
	$(this._id +'_title').innerHTML		= this._contests[rand][0];
	$(this._id +'_image').src			= this._contests[rand][1];
	$(this._id +'_desc').innerHTML		= this._contests[rand][4];
	$(this._id +'_link1').href			= this._contests[rand][2];
	$(this._id +'_link1').title			= this._contests[rand][0];
	$(this._id +'_link2').href			= this._contests[rand][2];
	$(this._id +'_link2').title			= this._contests[rand][0];
	$(this._id +'_link2').innerHTML		= this._contests[rand][3];
	
	//var ego = 'http://www.sol.dk/ego/front_konkurrence' + (contests[rand][5] ? '_' + contests[rand][5] : '');
	//$(this._id +'_link1').onmousedown	= function() { return this.href=ego + '_image/' + contests[rand][2]; }
	//$(this._id +'_link2').onmousedown	= function() { return this.href=ego + '_link/' + contests[rand][2]; }
}

// not part of class - cant use intervals in class's
function crUpdate(nr) {
	var obj = eval(nr)
	obj.hide();
	setTimeout(
		function(){
			obj.load();
			obj.show()
		}, 900
	);
}



if (!window.bagside)
	var bagside = new Object();

bagside.Methods = {
	_useCookies:		true,
	_cookieSaysNo:		false,		// ;-)
	_cookieName:		'noeffects',
	
	_isScrolling:		false,		// are the page scrolling?
	_haveScrolled:		0,			// how far have page been scrolled?
	
	_scrollDest:		false,		// where do we switching between front/back
	_scrollDestBorder:	false,		// display scrolling switch with a borderline
	
	_isFocusing:		false,		// are we currently focusing in on front/back (effect in progress)?
	_currentFocus:		'',			// current focus - 'top' or 'bottom'
	
	_useOverlay:		true,				// use overlay to dim not active elements of page
	_resetOverlay:		true,				// whether overlay should reset position when focusing
	_overlayParentID:	'bottompagebox',	// which id can contain overlay divs (must be container div)?
	_overlays:			{
							useAbsolutePosition: false,
							top: 	{ id: 'toppageOverlay', top: 'mainbody', left: 'mainbody', width: 'mainbody', height: 'contentcolumn' },
							bottom:	{ id: 'bottompageOverlay', top: 'bottompage', left: 'bottompage', width: 'mainbody', height: 'bottompage' }
						},
	
	_useEffects:		true,
	_effectOptions:			{
							overlayDuration: 0.3,
							overlayOpacity: 0.7,
							morphDuration: 0.8,
							top:			{	backgroundColor: '#ffffff' },	//#ffffff
							bottom:			{	backgroundColor: '#f1f2f4' }	//#f1f2f4
						},
	_effects:			{	top: false, bottom: false },
							
	
	_addWhitespace:		true,		// add padding to id 'footer' on first focus (to align bottom half to top of screen)
	
	_useAnchorScroll:	true,		// scroll if destination is an anchor (bottom half - but only onload)
	_anchorDelay:		400,		// delay before scrollTo is executed in milliseconds
	_anchorMap:	[
							{ anchor: 'bagsiden', id: 'bottompageanchor' },
							{ anchor: 'forsiden', id: 'toppageanchor' }
						],
	_viewportHeight:	0,		// to make bad(/all) browsers behave good
	
	//_debug:				'debugBox',	// id or false
	_debug: false,
	
	init: function() {
		if (location.hash == '#debug')
			this._debug = 'debugBox';
		this._log("init()");
		
		// ie6 fix
		if (navigator.userAgent.toLowerCase().indexOf("msie") != -1) {
			this._overlays.useAbsolutePosition = true;
		}
		
		this._viewportHeight = this._getViewportHeight();
		
		// load cookie preferences as first thing
		if (this._useCookies && get_c(this._cookieName) || get_c(this._cookieName) == 'true') {
			this._cookieSaysNo = true;
		}
	//	this._cookieSaysNo = false;
	//this._log('cval' + this._cookieSaysNo);	
		if (!this._cookieSaysNo) {
			this.enable();
		}
		
		this._onLoad = this._onLoad.bindAsEventListener(this);
		Event.observe(window, 'load', this._onLoad);
	},
	
	
	
	/**
	 *	_onLoad()
	 *	
	 *	Go through anchors that could be scrolled to (scrollAnchors).
	 *	If one is found, use that one.
	 *	
	 *	Also insert formular to deselect the use of effects (saved in cookie)
	 *	
	 */
	_onLoad: function() {
		var temp = this;
		var tmp = function() {
			temp.gotoAnchor(this.id.replace('til', ''));
		}
		Event.observe($('tilforsiden'), 'click', tmp);
		Event.observe($('tilbagsiden'), 'click', tmp);
		
		if (this._useAnchorScroll && this._useEffects && !this._cookieSaysNo) {
			var anchors = document.location.hash.toLowerCase();
			
			for (var i = 0; i < this._anchorMap.length; i++) {
				if (anchors.indexOf(this._anchorMap[i].anchor) != -1) {
					
					// a little delay to make it look a little nicer (browsers can do a lot on eg. 400 m.secs!)
					var temp = this;
					setTimeout('temp.gotoAnchor(\''+ this._anchorMap[i].anchor +'\')', this._anchorDelay);
					
					break;
				}
			}
		}
		
		// create preference checkbox in bottom of page and attach functions
		if (this._useCookies) {
			var options =	{ 
								id:			'bottompage_options', 
								inputid:	'bottompage_options_input', 
								label:		'Benyt ikke effekter på forsiden', 
								title:		'Klik her for at undgå brugen af effekter på forsiden'
							};
			
			var span = Builder.node('span', { id: options.id, title: options.title }, [
				Builder.node('input', { type: 'checkbox', id: options.inputid }),
				Builder.node('label', { htmlFor: options.inputid }, options.label )
			]);
			
			// a little more 'noticable'
			span.onmouseover = function()	{ this.className = this.id + '_hover'; }
			span.onmouseout = function()	{ this.className = this.id.replace('_hover', ''); }
			
			$('footer').insertBefore(span, $('footer').childNodes[0]);
			
			// onclick should enable or disable effects and functions
			temp = this;
			$(options.inputid).onclick = function() {
				if (this.checked) {
					temp.disable();
				}
				else {
					temp.enable();
				}
			}
			
			if (this._cookieSaysNo)
				$(options.inputid).checked = 'checked';
		}
		
		this._adjustWhitespace();
	},
	
	
	enable: function() {
		del_c(this._cookieName);
		
		// set switch between top/bottom (and a little offset)
		this._setScrollDest('bottompage', -1 * $('bottompage').offsetHeight / 2);
		
		this._useEffects	= true;
		this._useOverlay	= true;
		this._resetOverlay	= true;
		
		this._insertOverlay();
		this._repositionOverlay();
		
		this._onScroll = this._onScroll.bindAsEventListener(this);
		Event.observe(window, 'scroll', this._onScroll);
		//Event.observe(window, 'resize', this._onScroll);
		
		this._onResize = this._onResize.bindAsEventListener(this);
		Event.observe(window, 'resize', this._onResize);
		
		// switch anchors to
		if (this._useEffects) {
			for (var i = 0; i < this._anchorMap.length; i++) {
				var obj	= $(this._anchorMap[i].anchor);
				if (obj) {
					obj.name	= this._anchorMap[i].id;
					obj.id		= this._anchorMap[i].id;
				}
			}
		}
	},
	
	
	disable: function() {
		set_c(this._cookieName, 'true', 365, '/');
		
		Event.stopObserving(window, 'scroll', this._onScroll);
		//Event.stopObserving(window, 'resize', this._onScroll);
		Event.stopObserving(window, 'resize', this._onResize);
		
		$('pagecontainer').style.backgroundColor = this._effectOptions.top.backgroundColor;
		$('web').style.backgroundColor = this._effectOptions.top.backgroundColor;
		
		this._useEffects	= false;
		this._useOverlay	= false;
		this._resetOverlay	= true;
		
		this._repositionOverlay();
		
		for (var i = 0; i < this._anchorMap.length; i++) {
			var obj	= $(this._anchorMap[i].id);
			if (obj) {
				obj.name	= this._anchorMap[i].anchor;
				obj.id		= this._anchorMap[i].anchor;
			}
		}
	},
		
	/**
	 *	_onScroll(E)
	 *	
	 *	Saves how far the user have scrolled page.
	 *	Note: focusTop/focusBottom executes _focus() on each scroll...
	 *	
	 */
	_onScroll: function(E) {
		this._log("_onScroll("+ E +")");
		
		if (!this._isScrolling && this._scrollDest) {
			this._isScrolling = true;
			
			this._haveScrolled = self.pageYOffset ? self.pageYOffset : document.documentElement && document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body ? document.body.scrollTop : null;
			
			if (this._haveScrolled <= this._scrollDest) {
				this.focusTop();				// focus on top
			}
			else if (this._haveScrolled > this._scrollDest) {
				this.focusBottom();				// focus on bottom
			}
		}
		this._isScrolling = false;
	},
	
	
	/**
	 *	_onResize()
	 *	
	 *	Make sure the overlay is reset on next scroll
	 *	
	 *	Warning: IE6 (and possibly other browsers) can shoot multiple onresize events.
	 *	This can cause endless loops and/or browsercrash - use with care.
	 *	
	 */
	_onResize: function(Event) {
		this._log("_onResize()");
		
		var h = this._getViewportHeight();
		
		if (this._viewportHeight != h) {
			this._viewportHeight = h;
			
			this._addWhitespace = true;
			this._adjustWhitespace();
			
			this._resetOverlay = true;
			this._repositionOverlay();
		}
	},
	
	
	_adjustWhitespace: function() {
		if (this._addWhitespace) {
			var viewport = this._getViewportHeight();
			var div = $(this._overlayParentID).offsetHeight;
			var other = $('footer').offsetHeight;
			var whitespace = viewport - div - other - 30;
			
			if ($('footer')) {
				whitespace = (whitespace < 0 ? 0 : whitespace);
				$('footer').style.marginTop = whitespace +'px';
			}
			
			this._addWhitespace = false;
		}
	},
	
	gotoAnchor: function(id) {
		var r;
		
		if (this._useAnchorScroll && this._useEffects && !this._cookieSaysNo) {
			// go through mapping to find corresponding id
			for (var i = 0; i < this._anchorMap.length; i++) {
				if (id == this._anchorMap[i].anchor) {
					r = this._anchorMap[i].id;
					break;
				}
			}
		}
		
		if (!r)
			return true;	// follow link
		
		new Effect.ScrollTo(r);
		return false;
	},
	
	
	/**
	 *	focusTop()
	 *	
	 */
	focusTop: function() {
		this._focus('top');
	},
	
	
	/**
	 *	focusBottom()
	 *	
	 */
	focusBottom: function() {
		this._focus('bottom');
	},
	
	
	/**
	 *	_focus(id)
	 *	
	 *	Launches appropriate functions for focusing on an area
	 *	
	 */
	_focus: function(focus) {
		this._log("_setFocus("+ focus +")");
		
		if (this._isFocusing || focus == this._currentFocus) {
			return;
		}
		
		this._isFocusing = true;
		
		if (focus == 'top') {
			if (this._useEffects) {
				new Effect.Parallel([
						new Effect.Morph('pagecontainer', { sync: true, style: { backgroundColor: this._effectOptions.top.backgroundColor }}),
						new Effect.Morph('web', { sync: true, style: { backgroundColor: this._effectOptions.top.backgroundColor }})
					], { 
					duration: this._effectOptions.morphDuration
				});
				
				if (this._useOverlay) {
					new Effect.Parallel([
							new Effect.Fade(
								this._overlays.top.id, {
									sync:		true
								}
							),
							new Effect.Appear(
								this._overlays.bottom.id, {
									sync:		true,
									to:			this._effectOptions.overlayOpacity
								}
							)
						], {
						duration: this._effectOptions.overlayDuration
					});
				}
			}
		}
		else if (focus == 'bottom') {
			if (this._useEffects) {
				new Effect.Parallel([
						new Effect.Morph('pagecontainer', { sync: true, style: { backgroundColor: this._effectOptions.bottom.backgroundColor }}),
						new Effect.Morph('web', { sync: true, style: { backgroundColor: this._effectOptions.bottom.backgroundColor }})
						
						
					], { 
					duration: this._effectOptions.morphDuration
				});
				
				if (this._useOverlay) {
					new Effect.Parallel([
							new Effect.Fade(
								this._overlays.bottom.id, {
									sync:		true
								}
							),
							new Effect.Appear(
								this._overlays.top.id, {
									sync:		true,
									to:			this._effectOptions.overlayOpacity
								}
							)
						], { 
						duration: this._effectOptions.overlayDuration
					});
				}
			}
		}
		
		this._currentFocus = focus;
		
		this._isFocusing = false;
	},
	
	
	/**
	 *	
	 *	_findScrollDest(id, offset)
	 *	
	 *	Find and set the destination for when to change focus
	 *	
	 */
	_setScrollDest: function(id, offset) {
		this._log("_setScrollDest("+ id +", "+ offset +")");
		
		var obj = $(id);
		
		var tmppos			= obj.style.position;	// store current position
		obj.style.position	= 'absolute';			// have to set div to absolute due to possible ie-bugs w. offsetX
		this._scrollDest	= obj.offsetTop;		// set global scrolling destination
		obj.style.position	= tmppos;				// (re)set position
		
		if (offset)
			this._scrollDest = this._scrollDest + offset;	// this makes the break a little higher than the id's top
		
		if (this._scrollDestBorder) {
			var div = Builder.node('div', { style: 'border-top: 2px solid red; position: absolute; left: 0px; top:'+ this._scrollDest+'px; width: 1000px;' }, ' ');
			$(this._overlayParentID).appendChild(div);
		}
	},
	
	
	/**
	 *	_getViewportHeight()
	 *	
	 *	Find and return total window viewport height
	 *	
	 */
	_getViewportHeight: function() {
		this._log("_getViewportHeight()");
		
		var viewportwidth, viewportheight;
		
		if (typeof window.innerWidth != 'undefined') {
			// the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
			viewportwidth = window.innerWidth,
			viewportheight = window.innerHeight
		}
		else if (typeof document.documentElement != 'undefined' && typeof document.documentElement.clientWidth != 'undefined' && document.documentElement.clientWidth != 0) {
			// IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
			viewportwidth = document.documentElement.clientWidth,
			viewportheight = document.documentElement.clientHeight
		}
		else {
			// older versions of IE
			viewportwidth = document.getElementsByTagName('body')[0].clientWidth,
			viewportheight = document.getElementsByTagName('body')[0].clientHeight
		}
		//alert('<p>Your viewport width is '+viewportwidth+'x'+viewportheight+'</p>');
		return viewportheight;
	},
	
	
	/**
	 *	_insertOverlay()
	 *	
	 *	Insert hidden overlay divs
	 *	
	 */
	_insertOverlay: function() {
		this._log("_insertOverlay()");
		
		if (!this._useOverlay || $(this._overlays.top.id) || $(this._overlays.bottom.id))
			return;
		
		var tmp1 = Builder.node('div', { id: this._overlays.top.id, style: 'display: none' }, ' ');
		var tmp2 = Builder.node('div', { id: this._overlays.bottom.id, style: 'display: none' }, ' ');
		
		var parent = $(this._overlayParentID);
		
		parent.appendChild(tmp1);
		parent.appendChild(tmp2);
	},
	
	
	/**
	 *	_repositionOverlay()
	 *	
	 *	Using timeout due to IE quirks with onResize event
	 */
	_repositionOverlay: function() {
		temp = this;
		setTimeout('temp._positionOverlay()', 1);
	},
	
	
	/**
	 *	_positionOverlay ()
	 *	
	 *	Sets the position of overlay(s) to correct positions (top/left/width/height)
	 *	
	 */
	_positionOverlay: function() {
		this._log("_positionOverlay()");
		
		if (!this._resetOverlay) {
			return;
		}
		else if (!this._useOverlay) {
			if ($(this._overlays.top.id))
				$(this._overlays.top.id).style.display = 'none';
			
			if ($(this._overlays.bottom.id))
				$(this._overlays.bottom.id).style.display = 'none';
			
			return;
		}
		
		this._resetOverlay = false;
		
		var pos = '';
		
		{
			// due to bugs in ie, this could be useful
			if (this._overlays.useAbsolutePosition) {
				pos = $(this._overlays.top.top).style.position;
				$(this._overlays.top.top).style.position = 'absolute';
			}
			
			var obj = $(this._overlays.top.id);
			
			obj.style.top		= $(this._overlays.top.top).offsetTop + 'px';
			obj.style.left		= $(this._overlays.top.left).offsetLeft + 'px';
			obj.style.width		= $(this._overlays.top.width).offsetWidth + 'px';
			obj.style.height	= $(this._overlays.top.height).offsetHeight + 'px';
			
			if (this._overlays.useAbsolutePosition) {
				$(this._overlays.top.top).style.position = pos;
			}
		}
		
		{
			// due to bugs in ie, this could be useful
			if (this._overlays.useAbsolutePosition) {
				pos = $(this._overlays.bottom.top).style.position;
				$(this._overlays.bottom.top).style.position = 'absolute';
			}
			
			var obj = $(this._overlays.bottom.id);
			
			obj.style.top		= $(this._overlays.bottom.top).offsetTop + 'px';
			obj.style.left		= $(this._overlays.bottom.left).offsetLeft + 'px';
			obj.style.width		= $(this._overlays.bottom.width).offsetWidth + 'px';
			obj.style.height	= $(this._overlays.bottom.height).offsetHeight + 'px';
			
			if (this._overlays.useAbsolutePosition) {
				$(this._overlays.bottom.top).style.position = pos;
			}
		}
	},
	
	
	
	
	/**
	 *	_log(msg)
	 *
	 *	Writes script status to selected div
	 */
	_log: function(msg) {
		if (!this._debug)
			return;
		
		var obj = $(this._debug);
		
		if (!obj) {
			var div = Builder.node('div', { id: this._debug, style: 'position: absolute; left: 0px; top: 200px; width: 200px; z-index: 999' }, ' ');
			$(this._overlayParentID).appendChild(div);
		}
		
		$(this._debug).innerHTML += "<br>" + msg;
	}
}

Object.extend(bagside, bagside.Methods);
