/*
	Loops once initialised to fade the opacity of element 'id' from initial 'opacity'
	to 0 or 100% by increments of 'inc' with 'sec' milliseconds between iterations.
	newImage and caption supplied by imageFade function, so they can be fed back to it
	once fade has gotten halfway.
	Calls setOpacity() to set the opacity.
*/
function elementFade(id,opacity,inc,sec,newImage,caption){
	element = document.getElementById(id);
	opacity += inc;
	if (opacity < 0) opacity = 0;
	if (opacity > 100) opacity = 100;
	if (opacity < 100 && opacity > 0){
		setOpacity(element,opacity);
		// re-call this function for the next incremental opacity change
		elementFadeTimeout = window.setTimeout("elementFade('" + id + "'," + opacity + "," + inc + "," + sec + ",\'" + newImage + "\',\'" + caption + "\')",sec);
	}
	// fire up imageFade if the opacity is still 0 (ie, a fade out has just finished), and set its fadeOut argument to 0
	if (opacity == 0)
		imageFade(id,newImage,0,caption);
}

/*
	focus on a form element 'el', if it exists and is visible
*/
function focus_if_exist(el){
	var real_el = document.getElementById(el);
	if (real_el){
		if (real_el.style.display != 'none')
			real_el.focus();
	}
}

/*
	switches classes of gallery thumbnails, making 'thumbnail' the active one
*/
function galleryChange(thumbnail){
	var thumbs = document.getElementsByName('thumb');
	var g;
	for(g = 0; g < thumbs.length; g ++){
		thumbs[g].parentNode.className = 'thumb_holder';
		setOpacity(thumbs[g],40);
	}

	var galleryImage = document.getElementById('gallery_image');
	if (galleryImage.src !== thumbnail.src){
		galleryImage.src = thumbnail.src;
		setOpacity(galleryImage,0);
	}
	setOpacity(thumbnail,100);
	thumbnail.parentNode.className = 'thumb_holder_on';
}


/*
	Starts the homepage image cycling, taking in 'image_array' - the 2D array of
	filenames and captions as generated by PHP, 'item' - the current array item being
	displayed, and 'firstTime' - whether to immediately fade (=0) or wait until the
	next iteration (=0). Calls imageFade() to initialise opacity fades and change HTML.
*/
function homepageImgInit(image_array,item,firstTime){
	imageId = 'homepage_image';
	image = document.getElementById(imageId);

	// don't fade out immediately if the page has just loaded (first image already hard-coded on index.php)
	if (!firstTime)
		imageFade(imageId,'images/homepage_images/' + image_array[item][0],1,image_array[item][1]);
	
	// increment item and preload next image or start again at 0
	if (item < (image_array.length - 1)){
		item ++
		document.getElementById('temp_image_holder').src = 'images/homepage_images/' + image_array[item][0];
	}
	else
		item = 0;

	itemText = "";	
	// turn image_array into a reuseable 2D array that can be stuck back into this function
	for(i = 0; i < image_array.length; i ++){
		// replace ' symbols to make them JS-safe before re-calling this function
		cap = image_array[i][1];
		while (cap.search("'") != -1)
			cap = cap.replace("'","&#039;");
		// embed caption from array into itemText string, JS-friendly array grammar added appropriately
		itemText += ("['" + image_array[i][0] + "','" + cap + "'],");
	}
	// remove the last extra ','
	itemText = itemText.slice(0,-1);
	// comes out like this: "[['01.jpg','caption'],['02.jpg','caption'],['03.jpg','caption']]"
	
	// Start the timer ticking to re-call function for the next image
	homepageImgInitTimeout = window.setTimeout("homepageImgInit([" + itemText + "]," + item + ",0)",6000);
}


/*
	Manages opacity fades and HTML changes for HTML image 'id' to fade it out,
	change its src attribute to 'newImage', change the caption to the appropriate
	one found by PHP in 'image_captions.txt', then fade back up to full opacity.
	Calls elementFade() to control opacity fades.
*/
function imageFade(id,newImage,fadeOut,caption){
	// replace < symbols to stop possible HTML tags in caption rendering
	while (caption.search("<") != -1)
		caption = caption.replace("<","&lt;");
	
	if (fadeOut){
		// fade out and start the timer to re-call this function for the fade-up (fadeOut now set to 0)
		elementFade(id,100,-10,20,newImage,caption);
	}
	else{
		// set source of main image and change caption text
		document.getElementById(id).src = newImage;
		document.getElementById('homepage_image_text').innerHTML = caption;
		// fade back up
		elementFade(id,0,10,20,newImage,caption);
	}
}


/*
	Returns true if 'obj' is an array, and false if it isn't
*/
function isArray(obj) {
	if (obj.constructor.toString().indexOf('Array') == -1)
		return false;
	else
		return true;
}

/*
	Used to navigate between products, switching the form inputs and submitting the form
	in place of an href click. 'product' is the product to be passed through as a URL variable
*/
function reloadProduct(product){
	// start a string to contain the tabs URL variable, add to it, based on the current tabs open
	var tabs = (document.getElementById('tab_container1').style.display == 'none')? '0-' : '1-';
	tabs += (document.getElementById('tab_container2').style.display == 'none')? '0-' : '1-';
	tabs += (document.getElementById('tab_container3').style.display == 'none')? '0-' : '1-';
	tabs += (document.getElementById('tab_container4').style.display == 'none')? '0' : '1';
	if (tabs == '0-0-0-0'){
		switch (product){
			case 'displays':
			case 'multiboard':
			case 'puntobanco':
			case 'eyeball': tabs = '0-1-0-0'; break;
			case 'pitboss':
			case 'keypad':
			case 'pitbossti': tabs = '0-0-1-0'; break;
			case 'chips':
			case 'balls': tabs = '0-0-0-1'; break;
			default : tabs = '1-0-0-0'; break;
		}
	}
	// set the form attributes as required, then submit the form
	document.tabs_form.product.value = product;
	document.tabs_form.tabs.value = tabs;
	document.tabs_form.submit();
}


/*
	Sets the opacity of element 'obj' to 'opacity' (0 - 100)
*/
function setOpacity(obj, opacity) {
	opacity = (opacity == 100)?99.999:opacity;

	// IE/Win
	obj.style.filter = "alpha(opacity:"+opacity+")";
	// Safari<1.2, Konqueror
	obj.style.KHTMLOpacity = opacity/100;
	// Older Mozilla and Firefox
	obj.style.MozOpacity = opacity/100;
	// Safari 1.2, newer Firefox and Mozilla, CSS3
	obj.style.opacity = opacity/100;
}


/*
	Scrolls the news items (if 'show_news.php' is PHP-included on the page)
	'scroll' number of positions
*/
function scrollNews(scroll){
	var ii = 1;
	var from = 0;
	var to = 0;
	var itemArray = new Array();
	// work out what 'from' and 'to' are, based on the display: style rule of each 'newsItem_??' element
	while(document.getElementById('newsItem_' + ii)){
		currItem = document.getElementById('newsItem_' + ii);
		itemArray[ii - 1] = currItem;
		if (from == 0){
			if (currItem.style.display == 'block')
				from = ii;
		}
		else{
			if (to == 0){
				if (currItem.style.display == 'none')
					to = (ii - 1);
			}
		}
		ii ++;
	}
	if (to == 0)
		to = itemArray.length;
	// change the display: rules according to 'scroll' argument
	if (from + scroll >= 1 && to + scroll <= itemArray.length){
		for(newii in itemArray){
			realNewii = parseInt(newii) + 1;
			newCurr = document.getElementById('newsItem_' + realNewii);
			if (realNewii >= (from + scroll) && realNewii <= (to + scroll))
				newCurr.style.display = 'block';
			else
				newCurr.style.display = 'none';
		}
	}
	
	//blank out the right buttons if necessary
	document.getElementById('newsUpImg').src = 'images/button_round_up.gif';
	document.getElementById('newsDownImg').src = 'images/button_round_down.gif';
	if (from + scroll < 2)
			document.getElementById('newsUpImg').src = 'images/button_round_up_off.gif';
	if (to + scroll >= itemArray.length)
			document.getElementById('newsDownImg').src = 'images/button_round_down_off.gif';
}


/*
	Fades between all images inside array 'images', using element id 'imgId' (string) as the container
	for the current image (via image source) and element id 'tempId' (string) as the temporary container
	for the next image (via CSS background url). 'curr' should be 0 and 'starting' to -1 to start the sequence.
	Calls itself after a while.
*/
// global variable for timer
var nextFade;

function simpleImageFade(images,curr,imgId,tempId,starting){
	// wrap curr back to 0 if it's bigger than the images array's length
	if (curr >= images.length)
		curr = 0;
	// set currImage and nextImage
	var currImage = images[curr];
	var nextImage = ((curr + 1) >= images.length)? images[0] : images[curr + 1];
	if (starting){
		document.getElementById(tempId).style.background = "url(" + nextImage + ")";
	}
	else{
		$('#' + imgId).fadeTo(1000,0,function(){
			document.getElementById(imgId).src = currImage;
			$(this).fadeTo(1000,1,function(){
				document.getElementById(tempId).style.background = "url(" + nextImage + ")";
			});
		});
	}
	// new string for the array argument when recalling the function
	arrayStr = '';
	// write the array into the string
	for(currImg in images)
		arrayStr += ("'" + images[currImg] + "',");
	// recall the function with the same image array and an incremented curr
	nextFade = window.setTimeout("simpleImageFade([" + arrayStr.substring(0,arrayStr.length - 1) + "]," + (curr + 1) + ",'" + imgId + "','" + tempId + "',0)",5000);
}

/*
	Stops the images fading
*/
function stopImageFade(){
	$('#fade_wheel').stop();
	$('#fade_wheel').fadeTo(0,1);
	clearTimeout(nextFade);
}

/*
	Switches the homepage product box 'element' on and all others off
*/
function switchProducts(element){
	i = 1;
	while (document.getElementById('product' + i)){
		document.getElementById('product' + i).className = 'product';
		i ++;
	}
	element.className = 'product_on';
	
	j = 1;
	while (document.getElementById('product_image' + j)){
		document.getElementById('product_image' + j).style.display = "none";
		j ++;
	}
	document.getElementById('product_image' + element.id.substring(7,8)).style.display = "block";
}

/*
	Navigates the browser to 'url' if 'idToCheck' is CSS-displayed 'none'
*/
function tabNavigate(idToCheck,url){
	if (document.getElementById(idToCheck).style.display != 'none')
		document.location = url;
}


/*
	Toggles between 'className1' and 'className2' for 'element'
*/
function toggleClassName(className1,className2,element){
	if (element.className == className1)
		element.className = className2;
	else
		element.className = className1;
}

/*
	Toggles the first character of 'element''s innerHTML between '+' and '-', leaving the rest of the innerHTML intact
*/
function toggleText(element,from,to){
	var txt = element.innerHTML;
	if (txt.search(from) != -1)
		element.innerHTML = txt.replace(from,to);
	else
		element.innerHTML = txt.replace(to,from);
}

/*
	Toggles the visibility of 'element' [a string]
*/
function toggleVis(element){
	el = (typeof element == "string")? document.getElementById(element) : element;
	el.style.display = (el.style.display == 'none')? 'block' : 'none';
}

/*
	:-O
*/
function pageFlash(){
	if (document.getElementById('container_outer'))
		document.getElementById('container_outer').style.backgroundColor = '#' + (Math.round(Math.random() * 9)) + (Math.round(Math.random() * 9)) + (Math.round(Math.random() * 9)) + (Math.round(Math.random() * 9)) + (Math.round(Math.random() * 9)) + (Math.round(Math.random() * 9));
	newFlash = window.setTimeout("pageFlash()",100);
}
