// hw_slideshow.js  ver 0.2  -*- coding: utf-8-unix; -*-
//
// Daisuke Kakura "2008-07-29 Tue 16:14:07 Antigua, Guatemala"
// Some Rights Reserved under Creative Commons License.
// http://creativecommons.org/licenses/by/2.1/jp/

var buttons;
var checkCount = 0;
var chgSpeed	= 200;
var hwData;
var isLoading	= 0;
var len;
var ssimg;
var ssphoto;
var sstext;

function hwSlideShow(data, id_photo, id_text, speed) {
	var index  = 0;
	isLoading  = 0;
	checkCount = 0;
	ssphoto	  = document.getElementById(id_photo);
	sstext	  = document.getElementById(id_text);
	hwData	  = data;
	len		  = hwData.length;
	ssimg		  = new Array(len);
	chgSpeed	  = speed;
	buttons	  = document.getElementsByTagName("button");

	var loadImg = function() {
		ssimg[index]	  = new Image();
		ssimg[index].src = hwData[index];
		index = index + 2;
		if (index >= len) {
			clearInterval(loadTimer);
		}
	}

	for (i = 0; i < buttons.length; i++) {
		buttons[i].style.visibility = "hidden";
	}

	var msg = document.createElement("span");
	msg.style.color			  = "white";
	msg.style.backgroundColor = "red";
	msg.style.fontSize = "80%";
	msg.style.top		 = "0px";
	msg.style.left		 = "0px";
	msg.style.padding	 = "0px 3px";
	msg.innerText		 = "読み込み中...";
	msg.style.position	  = "absolute";
	ssphoto.style.position = "relative";
	ssphoto.appendChild(msg);

	// check if loading finished.
	checkTimer = setInterval('checkLoadingImg()', 500);
   // do not use 'for' loop to load img, it stucks.
	loadTimer = setInterval(loadImg, 10);
}

function checkLoadingImg() {
	checkCount++;

	var imgCount = 0;
	var checkImg = function() {
		if (ssimg[imgCount]) {
			if (!ssimg[imgCount].complete) {
				isLoading = 1;
			}
		}
		imgCount = imgCount + 2;
		if (imgCount >= len) {
			clearInterval(checkOneImgTimer);
		}
	}
	// check if images are loaded. do not use 'for' loop.
	checkOneImgTimer = setInterval(checkImg, 5);

	if (checkCount > 30) {
		// ignore loading error.
		if (isLoading) {
			var msg = document.createElement("span");
			msg.style.color			  = "black";
			msg.style.backgroundColor = "yellow";
			msg.style.fontSize = "80%";
			msg.style.top		 = "0px";
			msg.style.left		 = "0px";
			msg.style.padding	 = "0px 3px";
			msg.innerText		 = "エラー!!";
			msg.style.position	  = "absolute";
			ssphoto.style.position = "relative";
			ssphoto.innerHTML = "";
			ssphoto.appendChild(msg);
			clearInterval(checkTimer);
		}
	}
	if (!isLoading) {
		clearInterval(checkTimer);
		playSlideShow();
		checkCount = 0;
		isLoading  = 0;
	}
}

function playSlideShow() {
	var index = 0;

	var changeImg = function() {
		ssphoto.innerHTML = "<img src=\"" + hwData[index] + "\" \/>";
		sstext.innerHTML	= hwData[++index];
		index++;
		if (index >= len) {
			clearInterval(chgTimer);
			for (i = 0; i < buttons.length; i++) {
				buttons[i].style.visibility = "visible";
			}
		}
	}

	chgTimer = setInterval(changeImg, chgSpeed);
}
