var jlib = {};

jlib.home = function () {
	var homeImages = [
			{
				src: '/images/mainPhoto/newhome01_top_lrg.jpg',
				alt: ''
			},
			{
				src: '/images/mainPhoto/newhome02_top_lrg.jpg',
				alt: ''
			},
			{
				src: '/images/mainPhoto/newhome03_top_lrg.jpg',
				alt: ''
			}
		],
		curImg = 0,
		imgCount = 0,
		PI = Math.PI,
		duration = 1300,
		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]; }));

};

/************************************************************
 * image reset and submit buttons
 */
jlib.imageInputs = function () {
	var offscreen = {
		display: 'block',
		position: 'absolute',
		left: '-9999px',
		top: '-9999px'
	};
	$('input:reset[src], input:submit[src]').each(function () {
		var input = $(this),
			type = input.attr('type'),
			form = $(this.form),
			a = $('<a href="#" class="button"><img alt="' + input.attr('value') + '" class="' + input.attr('class') + '" src="' + input.attr('src') + '" /></a>');
		a.click(function (e) {
			e.preventDefault();
			if (type == 'submit') {
				form.submit();
			} else {
				form.trigger('reset');
				form[0].reset();
			}
		}).insertBefore(input);
		input.css(offscreen).attr('tabindex', -1);
	});
};

/************************************************************
 * rollovers
 */
jlib.rollover = function (sel) {
	$(sel).each(function () {
		var off = this.src,
			over = off.replace('_off.', '_over.');
		if (off.indexOf('_off.') == -1) {
			return;
		}
		this.overSrc = over;
		this.offSrc = off;
	})
	.hover(
		function () { this.src = this.overSrc; }, // over
		function () { this.src = this.offSrc; } // out
	);
};

/************************************************************
 *  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);
		}
	});
};

/************************************************************
 * Language selector
 */
jlib.switchLang = function () {
	var pathname, pathArray, preLang, postLang;
	$('a[rel="switchLang"]').click(function (e){
		postLang = '/' + $(this).attr('id') + '/';
		e.preventDefault();
		pathname = location.pathname;
		pathArray = window.location.pathname.split( '/' );
		preLang = pathArray[1];
		preLang = '/' + preLang + '/';
		pathname = pathname.replace(preLang, postLang);
		window.location = window.location.protocol + "//" + window.location.host + pathname;
	});
};

/************************************************************
 * Dropdown menu
 */
jlib.dropdownmenu = function () {
	$('ul.dropdownmenu').each(function () {
		var ul = $(this),
			select = $('<select class="' + ul.attr('class') + '"></select>'),
			buf = ['<option value="">', ul.attr('title'), '</option>'];

		ul.find('a').each(function () {
			var a = $(this);
			buf.push('<option value="', a.attr('href'), '">', a.text(), '</option>');
		});

		select
			.append(buf.join(''))
			.change(function () {
				var href = $(this).val();
				if (href) {
					location.href = href;
				}
			})
			.replaceAll(ul);
	});
};

/************************************************************
 * Contact Us form validation
 */
jlib.contactUs = function () {
	$('.contactUs form').submit(function (e) {
		var form = $(this),
			msg = form.find('p.errormsg'),
			fields = ['subject', 'firstName', 'lastName', 'email', 'contactNumber', 'message'],
			email = $('#email'),
			hasError = false;

		form.find('label').removeClass('error');
		msg.hide();

		$.each(fields, function (i, s) {
			var field = $('#' + this);
			if (!$.trim(field.val())) {
				$('label[for="' + this + '"]').addClass('error');
				if (!hasError) {
					field.focus();
				}
				hasError = true;
			}
			if (this == 'email' && !jlib.isEmail(field.val())) {
				$('label[for="email"]').addClass('error');
				if (!hasError) {
					field.focus();
				}
				hasError = true;
			}
		});

		if (hasError) {
			msg.show();
			e.preventDefault();
		}
		return !hasError;
	})
	.bind('reset', function () {
		$('label', this).removeClass('error');
		$('p.errormsg', this).hide();
	});

	$('#subject').focus();
};

jlib.isEmail = function (s) {
	var at = s.indexOf('@'),
		l = s.substring(0, at),
		d = s.substring(at + 1).replace(/\.$/, '');
	return (!!l.match(/^[\w+-](?:[\w+.-]*[\w+-])?$/) &&
		l.indexOf('..') == -1 &&
		!!d.match(/^\w(?:[\w-]{0,61}\w)?(?:\.\w(?:[\w-]{0,61}\w)?)+$/) &&
		d.indexOf('_') == -1 &&
		d.length < 256);
};


/************************************************************
 * Footer toogle
 */
jlib.footer = function (s) {
	$("#popSearchToggle").click(function(event){
		event.preventDefault();
		$("#popSearch").slideToggle("normal",function(){
			if($(this).is(':visible')) {
			 $('html,body').animate({ scrollTop: 1500 }, 1000);
			}
		});
	});
}



/************************************************************
 * onload
 */
$(function () {
	jlib.home();
	jlib.openNewWindow();
	jlib.imageInputs();
	jlib.rollover('img.rollover, .sidenav a img');
	jlib.switchLang();
	jlib.dropdownmenu();
	jlib.contactUs();
	$('.contactTag').css('zoom','1'); /* fix for IE6 */
	jlib.footer();
});

