document.observe("dom:loaded", function() {
		
	mainNav = $$('div.main-nav');
	onClassElement = mainNav.invoke('down', 'li[class="on"]');
	
	externalLink();
	closeFB();
	highlightForms();
	formError();
	insertSpan();
	showLogin();
	launchFB();
	modifyEditProfile();
	startFeaturesCycle();
});

var timer = null;

function showNav() {
	// Needed to stop IE throwing script error when launching fb, /shrug
	var navigationDiv = $("navigation");
	if (navigationDiv) {
	
		$("navigation").observe('mouseover',
			function (event) {
		
				var element = Event.element(event);
				
				// if you mouseover an anchor then clear the timeout if there is one
				if ( (element.up(2).hasClassName('main-nav')) && (timer !== 'null') ) {
					clearTimeout(timer);
				}
				
				// if target is anchor and is within main-nav div
				// and prevent animation if original tab is first element you mouseover
				if (element.up(2).hasClassName('main-nav') && (!element.up().hasClassName('on')) ) {
					
					// remove 'on' class from nav element				
					onClassElement.invoke('removeClassName', 'on');
				
					// set the width on the span to the same width as the anchor
					var elementWidth = element.getWidth();
					var elementSpan = element.up('ul').down('span');
					
					elementSpan.setStyle({
						width: elementWidth + "px"
					});
					
					// calculate the offset needed to position the span
					var prevAnchorOffset = elementSpan.up().offsetLeft;	
					var AnchorOffset = element.offsetLeft;
					var valueToMove = AnchorOffset - prevAnchorOffset;
					
					// animate our span, y:28 is the height of our nav minus the height of the span (32-4)
					new Effect.Move(elementSpan, {
						x: valueToMove,
						y: 28,
						mode: 'absolute',
						transition: Effect.Transitions.spring,
						beforeStart: function() {
							// stop any effects going on
							cancelSlider();
						},
						queue: {
							scope: 'slider'
						}
					});
				}
			
			}	
		).observe('mouseout',
			function (event) {
				var element = Event.element(event);
				
				// set a timer to fade back to original nav
				if (element.up(2).hasClassName('main-nav')) {
					timer = setTimeout(returnToOriginalNav, 500);
				}
	
			}
		);
	
	}
	
}

// animate the span back to the original nav
function returnToOriginalNav() {
	mainNav.invoke('down', 'span').each(
		function (spanElement) {
			new Effect.Move(spanElement, {
				x: 0,
				y: 28,
				mode: 'absolute',
				transition: Effect.Transitions.spring,
				beforeStart: function() {
					// stop any effects going on
					cancelSlider();
					
					// set width of span to the width of original nav
					var anchorWidth = spanElement.up().getWidth();
					spanElement.setStyle({
						width: anchorWidth + "px"
					});
				},
				queue: {
					scope: 'slider'
				}
			});
		}
	);
}

// stop any effects going on
function cancelSlider() {
	var queue = Effect.Queues.get('slider');
		queue.each(
			function(effect) {
				effect.cancel();
			}
		);
}

// add span element onto initial tab
function insertSpan() {
	/*onClassElement.invoke('down').each (
		function (initialNav) {
			var spanElement = document.createElement('span');
			Element.extend(spanElement);
			initialNav.insert(spanElement);
		}
	);*/
	
	$$('div.main-nav li.on a').each (
		function (initialNav) {
			var spanElement = document.createElement('span');
			Element.extend(spanElement);
			initialNav.insert(spanElement);
			initialNav.up('ul').writeAttribute('id', 'nav');
		}
	);
	
	var x = $("nav");
	var y = $("navigation");
	if(x) {
		showNav();	
	}
	else if (y) {
		 $("navigation").down().writeAttribute('id', 'main-nav');
	}
}


// Highlight form fields on focus
function highlightForms() {
	var highlightForm = $$('textarea, input[type=text], input[type=password]');
		highlightForm.invoke('observe', 'focus',
			function(event) {
				event.element().addClassName("highlight");
			}
		).invoke('observe', 'blur',
			function(event) {
				event.element().removeClassName("highlight");
				event.element().removeClassName("highlight-error");
			}
		);
}

// Highlight form fields with errors
function formError() {
	var formError = $$("ol.form li span.error");
		formError.each (
			function(formErrorHighlight) {
				var error = formErrorHighlight.innerHTML;
				var errorHTML = error.substring(0,4);		
				if (! (errorHTML == '<!--')) {
					var formErrorHighlightInput = formErrorHighlight.previous('input[type=text], input[type=password], textarea');
					if (typeof formErrorHighlightInput != 'undefined') {
						formErrorHighlightInput.addClassName("highlight-error");
					}
				}
			}
		);

}
function closeFB() {
	fbPageOptions = {
		outsideClickCloses: false,
		overlayOpacity: 80,
		shadowType: 'none',
		innerBorder: 0,
		infoPos: 'tl',
		controlPos: 'tr'
	};
	
	var closeFloatbox = $("continue");
	if (closeFloatbox) {
		closeFloatbox.observe('click',
			function(event) {
				parent.fb.end();				
			}
		);
	}
}

function externalLink() {
	var currentHostname = window.location.hostname;
	
	$$("div#wrapper a").each (
		function (anchor) {
			if ( (currentHostname !== anchor.hostname && anchor.className !== 'button-inner' && anchor.className !== 'show-popup') || anchor.readAttribute('title') === 'Print this article' ) {
				anchor.writeAttribute('target','_blank');
			}
		}
	);
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function showLogin() {

//alert('called showLogin');

	if(!$('reg-notloggedin')) {
		return false ;
	}

	//check if access cookie is set
	var infra_access = readCookie('infra_access') ; 
	
	if(infra_access == null) {	
		$('reg-notloggedin').show() ;
		$('reg-loggedin').hide() ;
	} else {
		$('reg-notloggedin').hide() ;
		$('reg-loggedin').show() ;	
		
		var infra_products = readCookie('infra_products') ; 
		
		if(infra_products) {
			var aInfraProducts = infra_products.split('%3A') ;
		}

		aInfraProducts.each(
			function(infraProduct) {
				if(infraProduct == 'InfraEurope' || infraProduct == 'InfraNews') {
					$('reg-infraeurope').show() ;
					$$(".nav-infraeurope").invoke("show");
				}
				if(infraProduct == 'InfraAmericas') {
					$('reg-infraamericas').show();
					$$(".nav-infraamerica").invoke("show");
				}
				if(infraProduct == 'InfraDeals') {
					$('reg-infradeals').show() ;
				}
			}
		) ;

	}
	
	return true ;

}

//if we're on the edit profile form show/ hide DP questions depending on what product the user is signed up to
function modifyEditProfile() {

		if(!$('dp-reg_email_infradaily')) {
			return false ;
		} 

		var infra_products = readCookie('infra_products') ; 
		
		if(infra_products) {
			var aInfraProducts = infra_products.split('%3A') ;
		}

		$('dp-reg_email_infradaily').hide() ;
		$('dp-reg_email_infraweekly').hide() ;
		$('dp-reg_email_infraamericadaily').hide() ;
		$('dp-reg_email_infraamericaweekly').hide() ;
		
			aInfraProducts.each(
				function(infraProduct) {	
					if(infraProduct == 'InfraEurope' || infraProduct == 'InfraNews') {
						$('dp-reg_email_infradaily').show() ;
						$('dp-reg_email_infraweekly').show() ;
					}
					if(infraProduct == 'InfraAmericas') {
						$('dp-reg_email_infraamericadaily').show() ;
						$('dp-reg_email_infraamericaweekly').show() ;
					}
				}
			) ;		


}

// Auto launch welcome floatbox if user doesn't have cookie set
function launchFB() {
	var fbCookie = readCookie('infra_news_fb');
	
	if (!fbCookie) {
		var header = $("header");
		if (header) {
			header.insert ({
        		'bottom' : '<a href="/public/cloud/" rel="floatbox" rev="autoStart:true width:500 height:300 caption=`Welcome to the New Look InfraNews`" style="display:none;"></a>'
			});
		}
		
		document.cookie = 'infra_news_fb=yes; expires=Thu, 2 Aug 2100 20:47:11 UTC; path=/'
	}
}



////////////////////// THE CYCLE OBJECT CLASS //////////////////////
// This is essentially a class which cycles through the div ids passed
// to it on creation
function CycleObject(ids, transType, onClass, offClass) {

  // Methods
  this.setVisible = function(index) {

    // Check if there is an indicator for the animation and set as appropriate
    if (this.indicators[this.currentlyVisible]) {
      this.indicators[this.currentlyVisible].removeClassName(this.onClass);
      this.indicators[this.currentlyVisible].addClassName(this.offClass);
    }

    if (this.indicators[index]) {
      this.indicators[index].removeClassName(this.offClass);
      this.indicators[index].addClassName(this.onClass);
    }

    switch(this.transType) {

      case 'normal':
        $(this.ids[this.currentlyVisible]).hide();

        $(this.ids[index]).show();

        this.currentlyVisible = index;
        break;

      case 'fade':
        new Effect.Fade(
          this.ids[this.currentlyVisible],
      		{
      			from: 1.0,
      			to: 0.0,
      			duration: 0.3,
      			queue: 'end'
      		}
      	);

      	new Effect.Appear(
          this.ids[index],
      		{
      			from: 0.0,
      			to: 1.0,
      			duration: 0.3,
      			queue: 'end'
      		}
      	);
        this.currentlyVisible = index;
        break;
    }
  }

  this.nextItem = function() {
    // If we're at the end of the list...
    if( this.currentlyVisible == this.ids.length - 1 ) {
      return false;
    } else {
      this.setVisible(this.currentlyVisible + 1);
      return true;
    }
  }

  this.prevItem = function() {
    // If we're at the beginning of the list...
    if( this.currentlyVisible == 0 ) {
      ;// do nothing
    } else {
      this.setVisible(this.currentlyVisible - 1);
    }
  }

  this.showItem = function(index) {
  	// show a particular item in the list and stop the animation
	this.cycleObject.stop();
  	this.setVisible(index);
  }

  this.startCycle = function() {
	this.cycleObject = new PeriodicalExecuter(
		this.onUpdateCycle.bind(this), 15 // this is the number of seconds between each interval
	);
  }

  this.stopCycle = function() {
    this.cycleObject.stop();
    this.cycleObject = null;
  }

  this.toggleCycle = function() {
    if (this.cycleObject == null) {
      this.startCycle();
    } else {
      this.stopCycle();
    }
  }

  this.onUpdateCycle = function (pe) {
    if (this.nextItem() == false) {
      this.setVisible(0);
    }
  }

  // Properties

  // An array of ids over which the object will cycle
  // First check that the id exists, if not, discard it
  this.ids = [];
  for(i = 0; i < ids.length; i++) {
    if($(ids[i]) != null) {
      this.ids.push(ids[i]);
    }
  }

  // Transition is 'fade' by default
  this.transType = typeof(transType) != 'undefined' ? transType : 'fade';

  this.onClass = typeof(onClass) != 'undefined' ? onClass : 'on';
  this.offClass = typeof(offClass) != 'undefined' ? offClass : 'off';

  // The index (of the array ids) of the currently visible div
  this.currentlyVisible = 0;

  // Initialisation
  this.cycleObject = null;

  // find if there are any indicators
  this.indicators = new Array(this.ids.length);

  for(i = 0; i < this.ids.length; i++){
    var indicatorLabel = this.ids[i]+'-indicator';
  	var indicator = $(indicatorLabel);
  	this.indicators[i] = indicator;
  }

  // Set the first one as visible and all the others as not
  for(i = 1; i < this.ids.length; i++){
    $(this.ids[i]).hide();
  }

  this.setVisible(0);

}

/////////// END OF CYCLEOBJECT CLASS //////////////////


// Start features cycle box
function startFeaturesCycle() {
	var featuresBox = $("module-features");
	if (featuresBox) {
		featuresCycleBox = new CycleObject(['headcyc-1', 'headcyc-2', 'headcyc-3', 'headcyc-4']);
		featuresCycleBox.startCycle();
	
		var featuresLinks = $$('a.featurescyclelink');
		featuresLinks.each(function(link) {
			var itemNumber = link.id.replace('headline-rotate','')-1;
			link.observe('click',
				function() {
					featuresCycleBox.showItem(itemNumber);
				}
			)
		});
	}
}
