jQuery.jQueryRandom = 0;
jQuery.extend(jQuery.expr[":"],
{
    random: function(a, i, m, r) {
        if (i == 0) {
            jQuery.jQueryRandom = Math.floor(Math.random() * r.length);
        };
        return i == jQuery.jQueryRandom;
    }
});

var z_index = new Array;
	z_index[0] = 999999;
	z_index[1] = 999999;

var timer;

$(function() {
	
	var now = new Date();
	var offsetNow = new Date(now.valueOf() + (parseInt('+1') * 1000 * 60 * 60));
	if(offsetNow.getHours() < 7 || offsetNow.getHours() > 18) {
		$('#branding').attr('class', 'closed');
	}
	else {
		$('#branding').attr('class', 'open');
	}
	
	runDigitalClock();
	
	$.ajax({url: 'images.xml',
			dataType: 'xml',
			cache: false,
			success: function(xml) {
				
				cycleNew(xml);
				
			}});
	
});

function cycleNew(xml) {
	
    cycle_index = 0;
    
    var images = new Array;
    
    images[0] = $(xml).find('image:random'); // .remove() removed here as there is a bug with it in jQuery in IE
    images[1] = $(xml).find('image:random');
    images[2] = $(xml).find('image:random');
    images[3] = $(xml).find('image:random');
    images[4] = $(xml).find('image:random');
    images[5] = $(xml).find('image:random');
    images[6] = $(xml).find('image:random');
    images[7] = $(xml).find('image:random');
    
    for(i in images) {
    	
/*     	$(xml).find('image').parent().find('image:eq(' + $(xml).index(images[i]) + ')').remove(); */
    	
    	$('#intro ul:eq(' + cycle_index + ')').append('<li style="z-index: ' + z_index[cycle_index] + ';"><img alt="' + images[i].find('alt').text() + '" src="http://www.hawkeronline.com/images/medium/' + images[i].find('part').text() + '.jpg" /></li>');
    	
    	z_index[cycle_index]--;
    	
    	if(cycle_index === 1) cycle_index = 0;
    	else cycle_index++;
    	
    }
	
	fadeImages('even', function() { cycleNew(xml); });
	
}

function fadeImages(type, callback) {
	
	clearTimeout(timer);
	
	if($('#intro ul:' + type + ' li:visible').length > 0) {
		
		if($('#intro ul:' + type + ' li:visible').length == 2) {
			return callback();
		}
		
		$('#intro ul:' + type + ' li:visible:first').hide();
		
		if(type == 'odd') type = 'even';
		else if(type == 'even') type = 'odd';
		else type = 'even';
		
		timer = setTimeout(function() { fadeImages(type, callback) }, 3000);
		
	}
	
}

function runDigitalClock() {
	
	setTimeout(runDigitalClock, 1000);
	
	var now = new Date();
	
	var hours = (now.getHours() < 10) ? '0' + now.getHours() : now.getHours();
	var minutes = (now.getMinutes() < 10) ? '0' + now.getMinutes() : now.getMinutes();
	var seconds = (now.getSeconds() < 10) ? '0' + now.getSeconds() : now.getSeconds();
	
	$('div#clock p.digital').text(hours + ':' + minutes + ':' + seconds);
	
}