/* (c) 2008 Michiel van der Blonk
-- for Sportsman Media
*/
var kittieApp = {
	// showPic can work with event (by user click), or without (by code call)
	showPic: function(e, thumb) {
		var getTarget = function (e) {
			var targ;
			if (!e) e = window.event;
			if (e.target)
				targ = e.target;
			else if (e.srcElement)
				targ = e.srcElement;
			if (targ.nodeType == 3)
				targ = targ.parentNode;
			return targ;
		};
		if (!thumb)
			var thumb = getTarget(e);
		if (thumb.tagName == 'IMG')
		{
			var mainpic = $('catshade');
			var kittie = kittieApp.db.kitties[thumb.alt];
			mainpic.title = mainpic.alt = "";
			// use DOM method to avoid flicker effect
			// see http://snippets.dzone.com/posts/show/1596
			if (mainpic.parentNode && mainpic.replaceChild)
			{
				var divParent;
				var imgNew = document.createElement('img');
				imgNew.src = thumb.src.replace('_thumb','');
				imgNew.id = mainpic.id;
				imgNew.width = kittie.width;
				imgNew.height = kittie.height;
				divParent = mainpic.parentNode;
				divParent.replaceChild(imgNew, mainpic);
			}
			else
			{
				mainpic.src = thumb.src.replace('_thumb','');
				mainpic.width = kittie.width;
				mainpic.height = kittie.height;
			}
			mainpic.title = mainpic.alt = kittie.name;
			// if there is no element to use, skip
			if (!$('catname'))
				return;

			$('catname').innerHTML = '"' + kittie.name + '"';
			$('shadeUrl').href = kittie.url;
			// when the cat picture is clicked, it should visit the stored db url
			$('mainPic').onclick = function() { window.location.href = kittie.url; }; 
			// set the class name so an effect appears on hover
			$('mainPic').className = 'active';
			// set tooltip title
			$('mainPic').title = 'click to find out more about what ' + kittie.name + ' is wearing';
		}
	},
	init: function (db) {
		// init app, make db available locally
		kittieApp.db = db;
		if (!window.$)
			window.$ = function(s) {return document.getElementById(s);};
		// if there is no list, exit
		if (!$('list'))
			return;
		var oList = $('list');
		oList.onclick = function(e) {kittieApp.showPic(e, null)};
		// find first element and show picture for it
		var thumbs = oList.getElementsByTagName('LI');
		if (thumbs.length > 0)
		{
			thumbImg = oList.getElementsByTagName('IMG')[0];
			//thumbImg.onclick(); // works only in IE, so nope
			kittieApp.showPic(null, thumbImg);
		}
	}
};
