/* Copyright (c) 2006-2009, Apple Inc. All rights reserved. */

Event.observe(window, 'load', function(e) {
	
	var container = $('services');
	var services = container.select('.service');

	var totalCount = services.length;
	var checkedCount = 0;

	var onServiceChecked = function(element)
	{
		// are we there yet?
		checkedCount++;
		if (checkedCount >= totalCount)
		{
			var wikiServerIsOn = !$('service-updates').hasClassName('disabled');
			if (wikiServerIsOn)
			{
				// if the wiki server is on, there is no need to show the stand alone webcal and webmail links.
				// those services are available in the top level navigation.
				$('service-webmail').addClassName('disabled');
				$('service-webcal').addClassName('disabled');
			}
			
			var howManyEnabled = services.findAll(function(s) {
				return !s.hasClassName('disabled');
			}).length;
			
			// vary the number of items per row so that it lays out well
			var numOfColumns = howManyEnabled;
			if ([0,7,8].include(howManyEnabled)) numOfColumns = 4;
			if ([5,6].include(howManyEnabled)) numOfColumns = 3;
			container.addClassName( 'columns-' + numOfColumns );

			// add a supporting class to list elements containing enabled services
			// and hook up some iphone-specific event handlers
			$$('a.service:not(.disabled)').each(function(service) {
				var parent = service.up('li');
				if (parent) parent.addClassName('enabled');
			});
			
			if (howManyEnabled == 0) {
				container.addClassName('none-enabled');
				$('no-services-enabled').appear();
			} else {
				$('some-services-enabled').appear();
			}

			container.removeClassName('loading');
		}
	};
	
	var handleOrientationChange = function(e){
		if(typeof window.orientation){
			var d = document.body;
			if(Math.abs(window.orientation) == 90){
				if(!Element.hasClassName(d, 'landscape')){
					Element.addClassName(d,'landscape');
				}
			} else {
				if(Element.hasClassName(d, 'landscape')){
					Element.removeClassName(d,'landscape');
				}
			}
		}
	};
	
	services.each(function(s) { Element.enableLinkIfAvailable(s, onServiceChecked); });
	
	// handle iphone landscape mode (if necessary)
	handleOrientationChange();
	Event.observe(window, 'orientationchange', handleOrientationChange);
	
});

