// ===== SITE FUNCTIONS ===== //
window.onload = init;

function init()
{
	randomImage();
	randomGalleryImages();
	externalPopup();
}

function $(id) {
	return document.getElementById(id);
}

function getStyle(el,styleProp)
{
	//var x = document.getElementById(el);
	var x = el;
	if (x.currentStyle)
		var y = x.currentStyle[styleProp];
	else if (window.getComputedStyle)
		var y = document.defaultView.getComputedStyle(x,null).getPropertyValue(styleProp);
	else
		return false;
	return y;
}

/* === LOAD EXTERNAL LINKS IN NEW WINDOW === */
function externalPopup() {
	var links = document.getElementsByTagName('a');
	for (var i = 0; i < links.length; i++) {
		if (links[i].href.indexOf('http://www.bmakers.co.uk/') == -1 &&
			links[i].href.indexOf('http://bmakers.co.uk/') == -1 &&
			links[i].href.indexOf('http://localhost/') == -1 &&
			links[i].href.indexOf('http://') == 0
			) {
			links[i].style.backgroundImage = 'url(images/external.png)';
			links[i].style.backgroundPosition = 'right center';
			links[i].style.backgroundRepeat = 'no-repeat';
			var display = getStyle(links[i], 'display');
			if (display != 'block') {
				links[i].style.paddingRight = '15px';
			}

			links[i].onclick = function() {
				window.open(this.href);
				return false;
			}
		}
	}
}

/* === LOAD A RANDOM IMAGE === */
function randomImage()
{
	// Find the random image element
	var image;
	if ( image = document.getElementById('randomImage') )
	{
		// Find out where to load the images based on the classname
		var imagePath = '', randomNumber;
		switch (image.className)
		{
			case 'frontpage':
				imagePath = 'images/frontpage/';
				randomNumber = Math.ceil( Math.random() * RAMDOM_IMAGE_COUNT_FRONTPAGE );
				break;
			case 'defaultpage':
				imagePath = 'images/banner/';
				randomNumber = Math.ceil( Math.random() * RAMDOM_IMAGE_COUNT_BANNER );
				break;
			default:
				return; // No classname given, exit function
		}

		// Load the JPEG image
		image.src = imagePath + 'image' + randomNumber + '.jpg';
	}
}

var gallery = 0;
var galleryImages = new Array();
function randomGalleryImages() {
	if ($('pageImages')) {
		// Build path and start loading the gallery.xml in each gallery
		try {
			//DEBUG('=== LOADING GALLERY ' + gallery + ' ===');
			var path = 'gallery/' + GALLERIES[gallery] + '/album/';
			var xmlFile = path + 'gallery.xml';
			//DEBUG(path);
			//DEBUG('XML file: ' + xmlFile);
			http_request = httpConnection();
			if (!http_request) {
				return false;
			}
			http_request.onreadystatechange = function() { httpStateChange(http_request); };
		    http_request.open('GET', xmlFile, true);
		    http_request.send(null);
	    } catch(e) {
			//DEBUG('Could not make request.\nError #' + e.number + '\n' + e.description);
		}
	}
}
function loadGalleryDetails(xmlData) {
	try {
		//DEBUG('Data Loaded! ' +  GALLERIES[gallery] + ' #' + xmlData.documentElement.getElementsByTagName('name').length);
		var images = xmlData.documentElement.getElementsByTagName('name');
		var filename;
		for (var i = 0; i < images.length; i++) {
			filename = images[i].firstChild.nodeValue;
			filename = 'gallery/' + GALLERIES[gallery] + '/album/small/' + filename;
			//DEBUG(filename);
			galleryImages.push(filename);
		}
	} catch(e) {
		//DEBUG('Could not load gallery data.\nError #' + e.number + '\n' + e.description);
	}

	//DEBUG('Loaded Galleries: ' + galleryImages.length);
	gallery++;
	if (gallery < GALLERIES.length) {
		randomGalleryImages();
	} else {
		try {
			//DEBUG('Loaded Images: ' + galleryImages.length + ' in ' + GALLERIES.length + ' galleries.');
			var sample1 = $('sample1');
			var sample2 = $('sample2');
			var sample3 = $('sample3');
			var sample4 = $('sample4');

			var rnd1 = Math.ceil( Math.random() * galleryImages.length ) - 1;
			var rnd2 = Math.ceil( Math.random() * galleryImages.length ) - 1;
			var rnd3 = Math.ceil( Math.random() * galleryImages.length ) - 1;
			var rnd4 = Math.ceil( Math.random() * galleryImages.length ) - 1;

			//DEBUG('rbd1 ' + rnd1);
			//DEBUG('rbd2 ' + rnd2);
			//DEBUG('rbd3 ' + rnd3);
			//DEBUG('rbd4 ' + rnd4);

			//DEBUG('rbd1 ' + galleryImages[rnd1]);
			//DEBUG('rbd2 ' + galleryImages[rnd2]);
			//DEBUG('rbd3 ' + galleryImages[rnd3]);
			//DEBUG('rbd4 ' + galleryImages[rnd4]);

			sample1.src = galleryImages[rnd1];
			sample2.src = galleryImages[rnd2];
			sample3.src = galleryImages[rnd3];
			sample4.src = galleryImages[rnd4];

			galleryImages = null;
		} catch(e) {
			// Clean up array
			//DEBUG('Could not pick random images.\nError #' + e.number + '\n' + e.description);
			galleryImages = null;
		}
	}

}

// Returns an http object
function httpConnection() {
	//try {
		var httpObject = false;
	    if (window.XMLHttpRequest) { // IE7, Mozilla, Safari, ...
	        httpObject = new XMLHttpRequest();
	        if (httpObject.overrideMimeType) {
	            httpObject.overrideMimeType('text/xml');
	            // See note below about this line
	        }
	    } else if (window.ActiveXObject) { // IE 6-
	        try {
	            httpObject = new ActiveXObject("Msxml2.XMLHTTP");
	        } catch (e) {
	            try {
	                httpObject = new ActiveXObject("Microsoft.XMLHTTP");
	            } catch (e) {
					//DEBUG('Could not create http object.\nError #' + e.number + '\n' + e.description);
				}
	        }
	    }
	    return httpObject;
    //} catch(e) {
    //	DEBUG('Could not create http object.\nError #' + e.number + '\n' + e.description);
    //}
}

// Function called when the page is loaded
function httpStateChange(http_request) {
	//DEBUG('ReadyState: ' + http_request.readyState);
	//DEBUG('Status: ' + http_request.status);
    if (http_request.readyState == 4) {
    	//DEBUG('Content: ' + http_request.responseText.replace(/\</g, '&lt;').replace(/\>/g, '&gt;'));
        if (http_request.status == 200) {

            loadGalleryDetails(http_request.responseXML);
            //alert(http_request.responseText);
        } else {
        	//DEBUG('There was a problem with the request.\nStatus: ' + http_request.status);
        }
    }
}

function DEBUG(text) {
	try {
		$('debug').innerHTML += text + '<br/>';
	}
	catch(e) {}
}