$(document).ready(function () {
    pageready();
});

var wantin_new;

function wantin(newel) {
	wantin_new = newel;
	setTimeout(function() { submenuhover(newel); },500);
}

function wantout(defaultel) {
	wantin_new = null;
	setTimeout(function() { submenuout(defaultel); },1000);
}

function submenuout(defaultel) {
	if (wantin_new == null) {
		$('.subnav li.selected').removeClass('selected');
		defaultel.addClass('selected');
	}	
}

function submenuhover(newel) {
	if (wantin_new == newel) {
		$('.subnav li.selected').removeClass('selected');
		newel.addClass('selected');
	}
}

function pageready() {
    var page = window.location.pathname.replace(/^.*\//i, '');
    var section = window.location.pathname.replace(/^\/([^\/]*).*$/i, '$1');
    if (section == '') {
		var splashoptions = $('.splashoptions')
        	$('.homeenvironmental,.homestructural,.homeland').mouseover(function(e) {
			if (e.target.nodeName.toLowerCase() == "img") {
				$(this).parents("div").children('div.splashoptions').fadeIn()
			}
		})
		$('.splash').mouseover(function() {
			splashoptions.fadeOut()
		})
    } else {
        $('li.' + section).addClass('selected');
        $('li.' + section).find('div a').each(function () {
			if (this.href.match('^' + window.location + "$")) $(this).addClass('selected');
		});
        $('.subnav').show();
        $('.subnav li').click(function () {
			location.href = $(this).children('a').attr('href');
		});
        $('.subnav li').mouseover(function () { wantin($(this)); });
			
        $('.subnav li').mouseout(function (e) { wantout($('li.'+section)); });
        carousel();
        $('.office').mouseover(function () { $(this).attr('src', '/images/office2.png'); });
        $('.office').mouseout(function () { $(this).attr('src', '/images/office.png'); });
        if (section == 'locations') {
			$(".office").click(function(e) {
				e.stopPropagation()
				var el = $(this)
				var tooltip = el.next(".tooltip").show()
				var top = this.offsetTop
				var left = this.offsetLeft
				var width = tooltip[0].offsetWidth
				var height = tooltip[0].offsetHeight
				tooltip.css({top: top - 195, left: left - 140})
			})
			$(document).click(function() {
				$(".tooltip").hide()
			})
        }
    }
}

function carousel(currentindex) {
    var items = $('ul.carousel li').length;
    if (currentindex == null) {
        $($('ul.carousel li').get(0)).show();
        if (items > 1)
            setTimeout(function () { carousel(0); }, 5000);
        return;
    }
    
    var current = $($('ul.carousel li').get(currentindex));
    var nextindex = currentindex + 1;
    if (nextindex >= items)
        nextindex = 0;
    var next = $($('ul.carousel li').get(nextindex));
    current.fadeOut('slow');
    next.fadeIn('slow', function() { setTimeout(function () { carousel(nextindex); }, 5000); });
}

