var jlib = {};

/************************************************************
 * open link from dropdown
 */
jlib.dropdownLink = function () {
	$('select').change(function () {
		var select = $(this), href = select.val();
		if (href == '') {
			return;
		}
		if (select.hasClass('openNewWindow')) {
			window.open(href);
		}
		else if (select.hasClass('openCurrentWindow')) {
			window.location.href = href;
		}
	});
};

/************************************************************
 * generate dropdown list from ul>li
 */
jlib.generateDropdown = function (sel) {
	$(sel).each(function () {
		var el = $(this),
			items = el.children(),
			buf = ['<select class="', el.attr('class'), '">'],
			title = el.attr('title');

		if (title != '') {
			buf.push('<option value="">', title, '</option>');
		}
		items.each(function () {
			var a = $(this).children('a');
			buf.push('<option value="', a.attr('href'), '">', a.text(), '</option>');
		});
		buf.push('</select>');

		el.replaceWith(buf.join(''));

		el = items = buf = null;
	});
};

/************************************************************
 *  open link in new window
 */
jlib.openNewWindow = function () {
	var rel, 
		href;
	$("a").click(function (e) {
		rel = $(this).attr('rel');
		href = $(this).attr('href');
		if (rel.indexOf('external') > -1) {
			e.preventDefault();
			window.open(href);
		}
	});
}

/************************************************************
 *  show / hide content from dropdown
 */
jlib.showHideContent = function (sel) {
	$(sel).each(function () {
		var cur;
		$(this).children().each(function () {
			if (!this.value) {
				return;
			}
			this.div = $(this.value.match(/#\w+$/)[0]);
		})
		.end()
		.change(function () {
			var o = this.options[this.selectedIndex];
			if (cur == o || !o.div) {
				return;
			}
			if (cur) {
				cur.div.addClass('hidden');
			}
			o.div.removeClass('hidden');
			cur = o;
		})
		.change();
	});
};

/************************************************************
 * home page images and tabs
 */
jlib.home = function () {
	var homeImages = [
			{
				src: '/images/th/homepage/insuring_your_family.jpg',
			//	alt: 'Insuring Your Families without Boundaries'
				alt: 'The Power of We'
			
			},
			{
				src: '/images/th/homepage/insuring_your_family_2.jpg',
				alt: 'The Power of We'
			},
			// comment after Feb 15, 2010
			{
				src: '/images/th/homepage/insuring_your_family_3.jpg',
				alt: 'The Power of We'
			},
			{
				src: '/images/th/homepage/insuring_your_family_4.jpg',
				alt: 'The Power of We'
			}
		],
		curImg = 0,
		imgCount = 0,
		PI = Math.PI,
		duration = 1000,
		delay = 3000,
		imgs, curTab;

	if (!$('body').hasClass('home')) {
		return;
	}

	// images

	// from http://www.robertpenner.com/easing/
	// t - current time (from 0)
	// b - start value (begin)
	// c - end value - start value (change)
	// d - duration
	function easeInOutSine(t, b, c, d) {
		return -c/2 * (Math.cos(PI * t / d) - 1) + b;
	}

	function fadeIn() {
		var cur = imgs[curImg], start = (new Date()).getTime(), d = duration;
		cur.css({
			opacity: '0',
			zIndex: '1',
			visibility: 'visible'
		});
		(function () {
			var t = (new Date()).getTime() - start;
			if (t >= d) {
				initFadeOut();
				return;
			}
			cur.css('opacity', easeInOutSine(t, 0, 1, d));
			setTimeout(arguments.callee, 0);
		})();
	}

	function initFadeOut() {
		var cur = imgs[curImg], next = imgs[(curImg + 1) % imgCount];
		cur.css({
			visibility: 'visible',
			zIndex: '1',
			opacity: '1'
		});
		next.css({
			visibility: 'visible',
			zIndex: '',
			opacity: '1'
		});
		// "fix" white dots
		if ($.browser.msie) {
			cur[0].style.removeAttribute('filter');
			next[0].style.removeAttribute('filter');
		}
		setTimeout(fadeOut, delay);
	}

	function fadeOut() {
		var cur = imgs[curImg], start = (new Date()).getTime(), d = duration;
		(function () {
			var t = (new Date()).getTime() - start, nextImg;
			if (t >= d) {
				nextImg = (curImg + 1) % imgCount;
				imgs[nextImg].css('z-index', '1');
				cur.css({
					visibility: 'hidden',
					zIndex: '',
					opacity: '1'
				});
				curImg = nextImg;
				initFadeOut();
				return;
			}
			cur.css('opacity', easeInOutSine(t, 1, -1, d));
			setTimeout(arguments.callee, 0);
		})();
	}

	imgs = $.map(homeImages, function (o) {
		return $('<img />')
			.load(function () {
				$(this).unbind('load', arguments.callee);
				imgCount++;
				if (imgCount == homeImages.length) {
					fadeIn();
				}
			})
			.css('visibility', 'hidden')
			.attr(o);
	});
	$('div.fadeimgs').append($.map(imgs, function (o) { return o[0]; }));

	// tabs
	$('ul.tabs a').each(function () {
		this.img = $(this).find('img')[0];
		this.div = $(this.hash);
	})
	.click(function (e) {
		e.preventDefault();
		if (curTab == this) {
			return;
		}
		if (curTab) {
			curTab.img.src = curTab.img.src.replace(/_(?:current|on)\./, '_off.');
			curTab.div.addClass('hidden');
		}
		this.img.src = this.img.src.replace(/_(?:off|on)\./, '_current.');
		this.div.removeClass('hidden');
		curTab = this;
	})
	.eq(0).click();
};

/************************************************************
 * show random div
 */
jlib.random = function () {
	$('div.hasRandom').each(function () {
		var items = $(this).find('div.random'), l = items.length;
		if (l == 0) {
			return;
		}
		items.eq(Math.floor(Math.random() * l)).addClass('randomShow');
	});
};


/************************************************************
 * onload, onunload
 */
$(function () {
	var body = $('body'), countries, p;

	if (!window.swfobj || !swfobj.hasFlashPlayerVersion('9.0.28')) {
		body.addClass('noflash');
	}

	jlib.home();
	jlib.random();
	jlib.generateDropdown('ul.selectMenu');
	jlib.dropdownLink();
	jlib.showHideContent('select.showHideContent');
	jlib.openNewWindow();
	
	// image rollovers
	$('img.rollover')
		.mouseover(function () { this.src = this.src.replace(/_off\./, '_on.'); })
		.mouseout(function () { this.src = this.src.replace(/_on\./, '_off.'); });

	body = null;
});