$(document).ready(function() {
	initPropertyFindTab();	
	initSlideShow();
	initImageViewer();
	initFormValidation();
	initDivBox();
});

var initDivBox = function() {
	$('.youtube').divbox({
		type: 'youtube',
		caption: false
	});
}

var initFormValidation = function() {
	var required = [
		{
			id: 'newsletter-fname',
			type: 'text'
		},
		{
			id: 'newsletter-lname',
			type: 'text'
		},
		{
			id: 'newsletter-email',
			type: 'email'
		}
	]
	$('#newsletter-form').submit(function() {
		var ret = true;
		for	(var i = 0; i < required.length; i++) {
			var req = required[i];
			var parent = $('#'+req.id).parent();
			parent.removeClass('error').find('small').remove();
			switch(req.type) {
				case 'text':
					if ($('#'+req.id).val() == '') {
						ret = false;
						parent.addClass('error').append('<small class="error">The First Name field is required.</small>');
					}
				break;
				case 'email':
					if (!/^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/.test($('#'+req.id).val())) {
						ret = false;
						parent.addClass('error').append('<small class="error">The E-mail field must contain a valid email address.</small>');
					}
				break;
			}
		}
		return ret;
	});
}

var initImageViewer = function() {
	$('#listing-main #images a').click(function(ev) {
		ev.preventDefault();
		$('#main-image').attr('src', $(this).attr('href'));	
	});
	$('#listing-main #image-selection').prepend('<a class="prev"></li>');
	$('#listing-main #image-selection').append('<a class="next"></li>');
	$('#listing-main #image-selection .next').click(function(ev) {
		ev.preventDefault();
		$('#listing-main #images').not(':animated').animate({
			scrollLeft: $('#listing-main #images').scrollLeft() + 108
		}, 600, 'linear');
	});
	$('#listing-main #image-selection .prev').click(function(ev) {
		ev.preventDefault();
		$('#listing-main #images').not(':animated').animate({
			scrollLeft: $('#listing-main #images').scrollLeft() - 108
		}, 600, 'linear');
	});
	$('#listing-main #images').css('overflow', 'hidden');
}

var initPropertyFindTab = function() {
	var tab = $('#property-find-tab');
	var handle = $('#property-find-handle');
	handle.click(function(ev) {
		ev.preventDefault();
		if (parseInt(tab.css('right')) === 0) {
			tab.animate({
				right: -230
			}, 600);
		} else {
			tab.animate({
				right: 0
			}, 600);
		}
	});
}

var initSlideShow = function() {
	setInterval('switchSlideShow()', 5000);
}

var switchSlideShow = function() {
	$active = $('#showcase li.active');
	if ($active.length == 0) $active = $('#showcase li:last');
	var $next =  $active.next().length ? $active.next() : $('#showcase li:first');
    $active.addClass('last-active');

    $next.css({opacity: 0.0}).addClass('active').animate({opacity: 1.0}, 1000, function() {
		$active.removeClass('active last-active');
	});
}
