$(document).ready(function(){
	$('.shorter-text').keypress(function(e){
     if(e.keyCode == 13)
          return false;
	});
	$('.shorter-email').keypress(function(e){
     if(e.keyCode == 13)
          return false;
	});
	$('.shorter-text').focus(function(){
		var prev = $(this).parent().parent().prev();
		refocus(prev);
	});
	$('.shorter-email').focus(function(){
		var prev = $(this).parent().parent().prev();
		refocus(prev);
		var txt = $('.shorter-text', $(this).parent().prev());
		txt.removeClass('error');
		txt.next('ul.errors').remove();
	});
	$('.shorter-email').blur(function(){
		if($(this).val() != '' && validate($(this).val())) {
			var emails = $('.shorter-email');
			var val = $(this).val();
			var current = $(this);
			var error = false;
			emails.each(function(){
				if(val == $(this).val() && $(this).attr('id') != current.attr('id')) {
					error = true;
					current.next('ul.errors').remove();
					current.addClass('error');
					showError(current, 'You cannot have the same email addresses.');
				}
			});
			if(!error) {
				if($('.shorter-text', $(this).parent().prev()).val() != '') {
					$(this).parent().next().remove();
					$(this).parent().after('<div class="plustwo"></div>');

					var next = $(this).parent().parent().next();
					if(!next.hasClass('msg')) {
						if(next.hasClass('full')) {
							next.before('<li class="msg">You have reached maximum of 5 invites. Click submit to earn your extra 10 chances to win.</li>');
						} else {
							var entries = parseInt($(this).attr('index')) * 2;
							next.before('<li class="msg">You are on your way to ' + entries + ' more chances to win. Earn another 2 by inviting another friend</li>');
						}
						next = $(this).parent().parent().next();
						next.hide();
						next.fadeIn();
					}

					var prev = $(this).parent().parent().prev();
					if(prev.hasClass('msg')) {
						prev.fadeOut();
					}
				} else {
					var txt = $('.shorter-text', $(this).parent().prev());
					txt.addClass('error');
					showError(txt, 'Please provide a valid name.');
					
				}
				$(this).removeClass('error');
				$(this).next('ul.errors').remove();

				var next = $(this).parent().parent().next().next().next();
				if(next.hasClass('hidden')) {
					next.removeClass('hidden');
				}
			}
		} else {
			$(this).addClass('error');
			showError($(this), 'Please provide a valid email address.');
		}
	});
	$("form.ajax").ajaxForm({
		type:      'post', 
		dataType:  'json',
		beforeSubmit:  showRequest,  // pre-submit callback 
		success:       showResponse  // post-submit callback 
		
	});
});
//
// pre-submit callback 
function showRequest(formData, jqForm, options) { 
    // formData is an array; here we use $.param to convert it to a string to display it 
    // but the form plugin does this for you automatically when it submits the data 
    var queryString = $.param(formData); 
 
    // jqForm is a jQuery object encapsulating the form element.  To access the 
    // DOM element for the form do this: 
    // var formElement = jqForm[0]; 
 
 	$(':input', jqForm).attr('disabled', 'disabled');

	$(".error", jqForm).removeClass('error');
	$("ul.errors", jqForm).remove();

	if(options.url.search(/\?/) != -1) {
		options.url = options.url + '&format=json';
	} else {
		options.url = options.url + '?format=json';
	}

 
    // here we could return false to prevent the form from being submitted; 
    // returning anything other than false will allow the form submit to continue 
    return true; 
} 
 
// post-submit callback 
function showResponse(data, statusText, xhr, jqForm)  { 
 	$(':input', jqForm).removeAttr('disabled');
	if(data.isError != undefined) {
		for(id in data.messages) {
			for(errorKey in data.messages[id]) {
				$('#' + id, jqForm).addClass('error').after('<ul class="errors"><li>' + data.messages[id][errorKey]+ '</li></ul>');
			}
		}
	} else {
		switch(data.action) {
			case 'redirect':
				self.location.href = data.url;
				break;
			case 'replace':
				$('#' + data.id).fadeOut('slow', function(){
					$(this).html(data.html).fadeIn();
				});
				break;
		}
	}
} 
function validate(email) {
   var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
   if(reg.test(email) == false) {
      return false;
   }
   return true;
}
function showError(ele, text) {
	if(!ele.next().hasClass('errors')) {
		ele.after('<ul class="errors"><li>' + text + '</li></ul>');
	}
}
function refocus(ele) {
	var text = $('.shorter-text', ele);
	if(text.hasClass('error')) {
		text.focus();
	}
	var email = $('.shorter-email', ele);
	if(email.hasClass('error')) {
		email.focus();
	}
}

