$(document).ready(function() {

	$('#dl-form').submit(submitDownloadForm);

	setupDownloadForm();
	
	var show_ratings = 10;
	if ($('h4.rating').size() > show_ratings)
		setupRatingDisplay(show_ratings);
		
});

function setupRatingDisplay(max) {
	$('.clients').append('<a href="#viewmore" id="more-reviews" class="f-right">View More</a>').
		find('.rating').each(function(i) {
			if (i < max)
				$(this).addClass('show-rating');
			else
				$(this).hide();
		});
		
	$('#more-reviews').click(function() {
		showMoreRatings(max);
		return false;
	});
}

function showMoreRatings(max) {
	$('.clients .rating').not('.show-rating').each(function(i) {
		if (i < max) {
			$(this).addClass('show-rating').show();
		}
	});
	
	if ($('.clients .rating').not('.show-rating').size() == 0) {
		$('#more-reviews').remove();
	}
}

function setupDownloadForm() {
	var input = document.getElementById('dl-form-name');
	setupInputBackgroundAndEvents(input, 'input-name.png');

	input = document.getElementById('dl-form-phone');
	setupInputBackgroundAndEvents(input, 'input-phone.png');

	input = document.getElementById('dl-form-email');
	setupInputBackgroundAndEvents(input, 'input-email.png');
}

function setupInputBackgroundAndEvents(element, bg_img) {
	var input = $(element);

	if(input.val() == '')
		cssInactive(input, bg_img);

	input.keydown(function() {
		cssActive(input);
	});

	input.blur(function() {
		if(input.val() == '') {
			cssInactive(input, bg_img);
		}
	});
}

function cssActive(input) {
	input.css({backgroundImage:'none'});
}

function cssInactive(input, bg_img) {
	input.css({backgroundImage:'url(/images/'+bg_img+')'});
}

function submitDownloadForm() {
	var name = $('#dl-form-name').val();
	var phone = $('#dl-form-phone').val();
	var email = $('#dl-form-email').val();
	var checkbox = $('input[name="contact"]');
	var contact = false;

	if(checkbox.is(':hidden'))
		contact = checkbox.val();
	else
		contact = checkbox.is(':checked');

	var ebox = $('#dl-form').find('.form-errors');

	ebox.empty();
	showFormLoader('dl-form');
	$.post('/ajax/sendEmail.php', {name:name,phone:phone,email:email,contact:contact}, function(errors) {

		hideFormLoader('dl-form');

		if(errors.length > 0) {
			ebox.html(errors);
			$('#we-will-not-share').remove();
		} else { // On success
			document.location = '/thank-you.php';
			$('.form-errors').html('');
		}
	});

	return false;
}

function showFormLoader(form) {
	$('#'+form).find('img.invisible').css('visibility', 'visible');
	$('#'+form).find('img.no-show').css('display', 'block');
}

function hideFormLoader(form) {
	$('#'+form).find('img.invisible').css('visibility', 'hidden');
	$('#'+form).find('img.no-show').css('display', 'none');
}
