
window.addEvent('domready', function() {
    setBodyBackground();
	hideSubnavs();
	attachSubnav();
	buildGalleries();
	defaultNav();
	bindLightbox();
	if($('btnLogin') != null) {
		$('btnLogin').addEvent('click', function(){
			alert('This area is for authorised clients only. You are being redirected to an example of this system.');
			window.location = '/how-we-build/project-management.aspx';
			return false;
		});
	}
});

var timer = null;

function setBodyBackground() {
	$$('body')[0].setStyle('background-image', 'url(/images/bgs/' + $random(1, 20) + '.jpg)');
}


function defaultNav() {
	var navs = ['/homes/', '/how-we-build/', '/technical-resources/'];
	$$('#a1', '#a2', '#a6').each(function(item, index) {
		if (window.location.href.indexOf(navs[index]) > 0 ) {
			hideSubnavs();
			clearTimer();
			sender = item.getProperty('id');
			showSubnav(sender);
		}
	});
}

function buildGalleries() {
	$$('p.gallery').each(function(item, index) {
		var idx = index;
		item.getChildren('img').each(function(item, index) {
			if (index > 0) {
				item.addEvent('mouseenter', function() {
					var iidx = idx;
					src = item.getProperty('src');
					$(iidx + '_big').setProperty('src', src.substr(0, src.indexOf('t.')) + src.substr(src.indexOf('t.') + 1));
				});
			}
			else {
				item.setProperty('id', idx + '_big');
				item.setStyles({'margin-bottom': '4px', 'cursor': 'default'});
			}
		});
	});
}

function bindLightbox() {
	$$('a > img').each(function(item, index) {
		var a = item.getParent('a');
		if (a != null) {
			href = item.getParent('a').getProperty('href');
			if ((href.substr(href.length - 4) == '.jpg') || (href.substr(href.length - 4) == '.gif')) {
				a.slimbox();
			}
		}
	});
}

function attachSubnav() {
	$$('#topnav a').each(function(item, index) {
		item.addEvent('mouseenter', function() {
			hideSubnavs();
			clearTimer();
			var sender = item.getProperty('id');
			showSubnav(sender);
		});
	});
	$$('#subnav div').each(function(item, index) {
		item.addEvents({'mouseleave': function() {
			timer = window.setTimeout("hideSubnavs()", 1000);
		}, 'mouseenter': function() {
			clearTimer();
		}});
	});
}

function clearTimer() {
	if (timer != null) {
		window.clearTimeout(timer);
		timer = null;
	}
}

function showSubnav(sender) {
	hideSubnavs();
	$(sender).setStyle('background-color', '#b8b896');
	if ($('d' + sender) != null) {
		$('d' + sender).setStyle('display', 'block');
	}
}

function hideSubnavs() {	
	$$('#topnav a').each(function(item, index) {
		item.setStyle('background-color', '#a3a378');
	});
	$$('#subnav div').each(function(item, index) {
		item.setStyle('display', 'none');
	});
}
