
jQuery(document).ready(function($) {

	$('a.vote').click(function () {
	
	
		$('span#vote_dj_name').text( $(this).attr('data-name') );
		$('input#vote_post_id').val( $(this).attr('data-id') );
		$('input#vote_secret').val( $(this).attr('data-secret') );
	
		$.fn.colorbox( { width:"400px", inline:true, href:"#lightbox"} );
	
		return false;
	});

	$('#vote_form').submit(function() {
		
		$(".error").hide();
		
		post_id = $("input#vote_post_id").val();

		
		var hasError = false;
		var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;

		var emailToVal = $("#vote_email").val();
		if(emailToVal == '') {
			$("#vote_email").after('<span class="error">This field is required.</span>');
			hasError = true;
		} else if(!emailReg.test(emailToVal)) {
			$("#vote_email").after('<span class="error">Please enter a valid e-mail address.</span>');
			hasError = true;
		}
		
		var messageVal = $("#vote_name").val();
		if(messageVal == '') {
			$("#vote_name").after('<span class="error">This field is required.</span>');
			hasError = true;
		}
		
		var messageVal = $("#vote_age").val();
		if(messageVal == '') {
			$("#vote_age").after('<span class="error">This field is required.</span>');
			hasError = true;
		}
		
		var gender = $("input[name='gender']:checked").val();
		if ( gender != 'male' && gender != 'female' ) {
			$("#vote_gender_error").after('<span class="error">This field is required.</span>');
			hasError = true;
		}
		
		var optin = $("input[name='opt-in']").attr('checked')
		if ( !optin ) {
			$("#vote_optin_error").after('<span class="error">This field is required.</span>');
			hasError = true;
		}

		if(hasError == false) {
							
			$.ajax({
				type: 'POST',
				url: "/vote.php",
				dataType: 'text',
				data:  $(this).serialize(),
				success: function (data) {
					
					$.fn.colorbox.close();
					
					if (data == 'Your vote is recieved.') {
						count = parseInt( $('#' + post_id + 'votes').html() );
						
						count++;
						$('#' + post_id + 'votes').html( count++ );
					}

					alert(data);
					
				},
				error: function () {
					alert('Something went wrong');
				}
				
			});

			
		}

		return false;
	});

 });
