/*
 Older version from asylum - before including flyout copied on 12 June
	Fudge vs. Area 17 vs. Prototype & Scriptaculous

	written by Phil (phil at fudgestudios.com) and Mike "1312" (mike at fudgestudios.com)

	for Area 17 (www.area17.com)
	

	This javascript is the main javascript for the sites actions.
	
*/

// --------------------------------------------------------------------------------------------------------------
// set up variables

var isSafari = false;
var isSafari3 = false;
var isIE = false;
var isIE7 = false;	

// --------------------------------------------------------------------------------------------------------------
// what to do on DOM ready
document.observe("dom:loaded", runOnDOMready);
// what to do when body loaded
Event.observe(window, 'load', function() { runOnLoaded(); });

function runOnDOMready() {
	
	/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ some simple browser testing */
	// Safari versioning
	isSafari = Prototype.Browser.WebKit;
	// are we on safari 3? add a class (it over anti aliases everything which causes padding issues)
	// http://www.hedgerwow.com/360/dhtml/detect-safari3-by-js-css.html
	if( window.devicePixelRatio && window.getMatchedCSSRules && !window.Opera){
		isSafari3 = !!window.getMatchedCSSRules(document.documentElement,'');
	}
	if (isSafari) {	
		$$('body').invoke('addClassName', 'isSafari');
		if (isSafari3) { $$('body').invoke('addClassName', 'isSafari3'); }
	}
	// (ok so theres an assumption that any Safari thats not Safari3 is Safari2 here)		
	// IE versioning
	isIE = Prototype.Browser.IE;
	if (typeof document.body.style.maxHeight != "undefined") { if (!isSafari) { isIE7 = true; } }
	if (isIE) {	
		$$('body').invoke('addClassName', 'isIE');
		if (isIE7) { $$('body').invoke('addClassName', 'isIE7'); }
	}
	/* http://gmatter.wordpress.com/2006/10/20/detecting-ie7-in-javascript/ */
	// ### ok so theres an assumption that any IE thats not IE7 is IE6 here	
	
	
	/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ set up some adding of classes to things */	
	
	setUpClasses();		
	
	/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ do some roll over events */
	
	// class="image" (for input type=image)
	$$('.image').each(function(el){
		el.observe('mouseover', function(event) {
			var element = Event.element(event);
			element.addClassName('hover');
		});
		el.observe('mouseout', function(event) {
			var element = Event.element(event);
			element.removeClassName('hover');
		});
	});
		
		
		
	/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ apply the green number to the ordered list */
	
	if($$('.mostPopularArticles')) {
	//	alert("exists");
	}

	
	
	/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ navigation flyout */
	
	list = $('navPrimary').getElementsBySelector('ul');
	navItems = list[0].getElementsBySelector('li');
	$(navItems).each(function(el) {
		// get first list inside each list item
		el.observe('mouseover', function(event) {
			popOutSubMenu.delay(0.25,el);
		});		
		el.observe('mouseout', function(event) {
			innerList = el.getElementsBySelector('ul');			
			if(innerList.length > 0) {			
				innerList[0].style.display='none';
				innerList[0].up().removeClassName('hover');
			}
		});		
	})
	
	function popOutSubMenu(el) {
		el.observe('mouseover', function(event) {		
			innerList = el.getElementsBySelector('ul');
			if(innerList.length > 0) {
				//innerList[0].style.display='inline';
				innerList[0].style.display='block';
				innerList[0].up().addClassName('hover');
			}
		});	
	}
	
	
	
	/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ search options */
	
	$$('#searches ul li.first a').each(function(el){
		el.observe('click', function(event) {
			var element = Event.element(event);
			element.up().addClassName('current');
			$$('#searches ul li.second')[0].removeClassName('current');
			$('search-asylum').removeClassName('hide');
			$('search-web').addClassName('hide');
			Event.stop(event);
		});
	});
	$$('#searches ul li.second a').each(function(el){
		el.observe('click', function(event) {
			var element = Event.element(event);
			element.up().addClassName('current');
			$$('#searches ul li.first')[0].removeClassName('current');
			$('search-web').removeClassName('hide');
			$('search-asylum').addClassName('hide');
			Event.stop(event);
		});
	});
	
	
	
	/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ last article doesnt want an underline */
	
	if($$('div.article').length!=0) {
		var n = $$('div.article').length-1;
		$$('div.article')[n].addClassName('lastArticle');
		//$$('div.article:last').invoke('addClassName', 'lastArticle');	
		//$$('div.article:last-child').invoke('addClassName', 'lastArticle');
	}
	
	
	/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ top banner rollover */
	
	$$('div#banner div').each(function(el){
		el.observe('mouseover', function(event) {
			var element = Event.element(event);
			element.addClassName('hover');
		});
		el.observe('mouseout', function(event) {
			var element = Event.element(event);
			element.removeClassName('hover');
		});
	});
	
	
	/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ right banner rollover */
	
	$$('div.bannerHolder').each(function(el){
		el.observe('mouseover', function(event) {
			var element = Event.element(event);
			element.addClassName('hover');
		});
		el.observe('mouseout', function(event) {
			var element = Event.element(event);
			element.removeClassName('hover');
		});
	});
	
	

	/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ add behaviour to Most Commented Articles 
	
	if($('mostCommentedArticles')) {
		uls = $('mostCommentedArticles').getElementsBySelector('ul');
		uls2 = $(uls[0]).getElementsBySelector('ul');

		a = $(uls2)[2];
		newHeight = a.getHeight()+70;
		$('mostCommentedArticles').setStyle({
		  height: newHeight+'px'
		});
		a.style.display='inline';
		a.style.position='absolute';				
		a.addClassName("current");

		// add click event to all
		$(uls2).each(function(el) {			
			el.up().firstDescendant().observe('click', function(event) {

				duration = 30;
				linkList = el.up().getElementsBySelector('a');
				if (linkList.length > 0) {
					link = linkList[0];
					duration = link.readAttribute('duration');
				}

				linkList = el.getElementsBySelector('li');
				if (linkList.length == 0) {
					url = '/comments-flyout.xml?duration='+duration;

					new Ajax.Request(url,
					  {
					    method:'get',
					    asynchronous:false,
					    onSuccess: function(transport){
					      var response = transport.responseText || "no response text";
					      el.insert(response, el);
					    },
					    onFailure: function(){ }
					  });
				}

				// hide all ul's
				others = this.up().up().getElementsBySelector('ul');
				w=0;
				others.each(function(el) {
					el.previousSiblings()[0].removeClassName("current");
					el.style.display='none';
					if (w == 1) {
						$(el).style.left=10.4*w+"em";				
					} else if (w == 0) {
						$(el).style.left="20.8em";				
					}
					w++;
				})
				newHeight = $(this).nextSiblings()[0].getHeight()+70;
				$('mostCommentedArticles').setStyle({
				  height: newHeight+'px'
				});	
				this.nextSiblings()[0].style.display='inline';
				this.nextSiblings()[0].style.position='absolute';				
				this.addClassName("current");
				Event.stop(event)
			});			
		});
		
	}
	
*/	

/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ less/more on social networking article footer */
	
	// shows and hides the more/less links in the social networking article footer
	$$('.socialNetworking li.more a').each(function(el) {
		el.observe('click',  function(event) {
			nextLi = el.up().up().next();
			if(nextLi.style.display=='' || nextLi.style.display=='none') {
				nextLi.style.display='inline';
				el.up().removeClassName('more');
				el.up().addClassName('less');
				el.update('Less');				
			} else {
				nextLi.style.display='none';
				el.up().removeClassName('less');				
				el.up().addClassName('more');				
				el.update('More');				
			}
			Event.stop(event);			
		});		
	});
	// close lists back up
	$$('.less').each(function(el) {
		el.observe('click',  function(event) {

			nextLi = this.up().next();
			alert(nextLi.className);
			Event.stop(event);			
		});
	});	
	
	
	/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ search ok button roll over */
	
	if ($$('div#searches input.image').length != 0) {
		$$('div#searches input.image').each(function(el){
			var imgSrc = el.readAttribute('src');
			el.observe('mouseover', function(event) {
				var element = Event.element(event);
				element.addClassName('hover');
				element.writeAttribute('src', '/images/sitewide/trans.gif');
			});
			el.observe('mouseout', function(event) {
				var element = Event.element(event);
				element.removeClassName('hover');
				element.writeAttribute('src', imgSrc);
			});
		});
	}


	/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ most popular articles bg number */
	
	if (($$('div.mostPopularArticles').length) != 0) {
		$$('div.mostPopularArticles ol li').each(function(el,s){
			//var className = s + 1;
			//className = "article" + className;
			//el.addClassName(className);
			var position = s * 183;
			position = "5px -" + position+"px";
			el.setStyle({ backgroundPosition: position });
		});
	}
	
	
	/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ center paginator on article comments */
	
	if (($$('div.comments div.paginator').length) != 0) {
		var ul = $$('div.comments div.paginator ul')[0];
		var ulWidth = ul.getWidth();
		//alert(ulWidth);
		var liWidth = 0;
		$$('div.comments div.paginator ul li').each(function(el,s) {
			liWidth = liWidth + el.getWidth();											  
		});
		//alert(liWidth);
		var paddingLeft = (ulWidth - liWidth)/2;
		paddingLeft = paddingLeft + "px";
		ul.setStyle({paddingLeft: paddingLeft });
	}
	
	
	/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ top slider funcs */
	
	// slider li/a/img hovers
	$$('ul#slides li').each(function(el){
		el.observe('mouseover', function(event) {
			var element = Event.element(event);
			element.addClassName('hover');
		});
		el.observe('mouseout', function(event) {
			var element = Event.element(event);
			element.removeClassName('hover');
		});
	});
	$$('ul#slides li img').each(function(el){
		el.observe('mouseover', function(event) {
			var element = Event.element(event);
			element.up().addClassName('hover');
		});
		el.observe('mouseout', function(event) {
			var element = Event.element(event);
			element.up().removeClassName('hover');
		});
	});
	$$('ul#slides li a').each(function(el){
		el.observe('mouseover', function(event) {
			var element = Event.element(event);
			element.up().up().addClassName('hover');
		});
		el.observe('mouseout', function(event) {
			var element = Event.element(event);
			element.up().up().removeClassName('hover');
		});
	});	
	
	// slider motion
	var sliderInner = $('slides');
	// get all the items in the slider list
	var listItems = $$('#slides li');
	// get the html of the list items into a var
	var listItemsHTML = $('slides').innerHTML;
	// is the slider moving
	var sliderMoving = false;
	// which bit of the slider are we working on?
	var currentSliderCount = 2;
	var currentSliderPos = -20;
	var slideAmount = 312;
	// a var to attach the autoscroller set interval to
	var doAutoScroll = null;
	
	// add some events to the slider buttons
	if ($('slider')) {
		$$('#slider p.prev a')[0].observe('click', function(event) {
			moveSlider('left');
			Event.stop(event);				
		});
		$$('#slider p.next a')[0].observe('click', function(event) {
			moveSlider('right');
			Event.stop(event);				
		});		
		// the slider functions
		function moveSlider(direction) {
			if (!sliderMoving) {
				clearInterval(doAutoScroll);
				calculateNextPosition(direction);
				sliderMoving = true;
				new Effect.Move (sliderInner,{ x: -currentSliderPos, y: 0, mode: 'absolute', duration: 0.99, transition: Effect.Transitions.sinoidal, afterFinish: checkForLoop });
			}
		}		
		// calculate the next position of the slider
		function calculateNextPosition(direction) {
			if(direction == 'right') {
				currentSliderCount ++;
				currentSliderPos += slideAmount;
			} else {			
				currentSliderCount--
				currentSliderPos -= slideAmount;
			}					
		}		
		// auto scroll
		function autoScroll() {
			moveSlider('right');	
		}
		// add extra list items into the dom!
		function addListItems() {
			// checl the amount of LIs
			if (listItems.length > 2 ) {
				// add in a copy of the LIs - twice
				// there are now 3 copies of the LIs and we want to mainly see the middle set,
				// and then over run onto one of the 2 copies, either left or right
				// before resetting back to showing the middle set
				$('slides').insert(listItemsHTML, { position: "bottom" } );
				$('slides').insert(listItemsHTML, { position: "bottom" } );	
				// sorts out positions and variables that other slider functions use
				resetSlider();
				// set up the prototype periodical executor
				//new PeriodicalExecuter(autoScroll, 5);
				// gah need to stop and start it, setInterval it is then...
				doAutoScroll = setInterval(autoScroll, 5000 );
			} else {
				// less than 2, dont do any auto scroll or any btn funcs
				$$('#slider p.next a')[0].style.display = 'none';
				$$('#slider p.prev a')[0].style.display = 'none';
			}
		}
		// check for loop, reset if need be
		function checkForLoop() {
			// if current is bigger than the amount plus one, then we're repeating the first 2 LIs, so we can just show the middle set again
			// or
			// if current is the same as negative amount minus 2, we've now gone backwards a full set, so we can just show the middle set again
			if( (currentSliderCount > (listItems.length + 1)) || (currentSliderCount == (listItems.length-2)*-1) ) {
				resetSlider();
			}
			sliderMoving = false;
			doAutoScroll = setInterval(autoScroll, 5000 );
		}
		// reset slider position and variables
		function resetSlider() {
			// as default:
			currentSliderCount = 2;
			// working out the width of the original set of LIs
			var width = slideAmount * listItems.length;
			// then adjusting (so the left button doesnt obscure) - this var is dom ready wide and is defined and used elsewhere
			currentSliderPos = width - 20;
			// then need to sort the position out, so that the middle set of LIs is shown.
			var posAdjust = "-"+currentSliderPos+"px";
			// and adjust
			sliderInner.setStyle({ left: posAdjust });
		}		
		// need to make sure extra list items have been added if needed
		addListItems();		
	}
}

function runOnLoaded() {	
	/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ redoing for IE! */
	/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ set up some adding of classes to things */	
	if (isIE) {
		setUpClasses();	
	}
}

// --------------------------------------------------------------------------------------------------------------
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ application wide functions */
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ (remember to test if the elements you are messing with exist) */
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ( eg. if (($$('body.homepage'))!=""){ } ) */

function setUpClasses() {
	$$('input[type=submit]').invoke('addClassName', 'submit');
	$$('input[type=radio]').invoke('addClassName', 'radio');
	$$('input[type=checkbox]').invoke('addClassName', 'checkBox');
	$$('input[type=image]').invoke('addClassName', 'image');
	$$('input[type=file]').invoke('addClassName', 'file');	
	$$('tr:nth-child(even)').invoke('addClassName', 'even');
	$$('li:nth-child(even)').invoke('addClassName', 'even');	
	$$('li:first-child').invoke('addClassName', 'first');
	$$('li:last-child').invoke('addClassName', 'last');		
}