$(function() {
	/*
	$('#email').bind('keydown keyup keypress blur focus', function() {
		$('#default').toggle((!$('#email').val()));
	});
	*/
	// Make sure button is enabled on load and if user hit back
	$("#submit").removeAttr('disabled');
	
	$('#default').click(function() {
		$('#email').focus();
	});
	
	$('#email').focus();

	$('#submit').hover(function() {
		$(this).addClass('hover');
	}, function() {
		$(this).removeClass('hover');
	});
	
	$('body.submit_hover').live('mouseup', function() {
		$('#submit').removeClass('mousedown'); 
		$(this).removeClass('submit_hover');
	});


	// Change Events
	// re-disable on load
	$("#email").attr('disabled', 'disabled');
	
    $("#cc-quality-input").change(function () {
    	var creditQuality = $(this).val();
    	
    	if(creditQuality == 'Excellent' || creditQuality == 'Good')
    	{
    		$('#credit-item').show();
    		$('#offer-type-credit-input').removeAttr('disabled');
    		
    		$('#credit-or-cash-item').hide();
    		$('#offer-type-credit-or-cash-input').attr('disabled', 'disabled');
    	} 
    	else if(creditQuality == 'Average' || creditQuality == 'Below Average' || creditQuality == 'Bad') 
    	{
    		$('#credit-item').hide();
    		$('#offer-type-credit-input').attr('disabled', 'disabled');
    		
    		$('#credit-or-cash-item').show();
    		$('#offer-type-credit-or-cash-input').removeAttr('disabled');    		
    	} 
    	else 
    	{
    		$('#credit-item').hide();
    		$('#offer-type-credit-input').attr('disabled', 'disabled');
    		
    		$('#credit-or-cash-item').hide();
    		$('#offer-type-credit-or-cash-input').attr('disabled', 'disabled');
    	}
    	
		$('#email-item').hide();
		$('#email').attr('disabled', 'disabled');
    });


    $("#offer-type-credit-input").change(function () {
    	var offer = $(this).val();
    	
    	if(offer != '')
    	{
    		$('#email-item').show();
    		$('#email').removeAttr('disabled');
    	} 
    	else
    	{
    		$('#email-item').hide();
    		$('#email').attr('disabled', 'disabled');
    	}
	});
	
    $("#offer-type-credit-or-cash-input").change(function () {
    	var offer = $(this).val();
    	
    	if(offer != '')
    	{
    		$('#email-item').show();
    		$('#email').removeAttr('disabled');
    	} 
    	else
    	{
    		$('#email-item').hide();
    		$('#email').attr('disabled', 'disabled');
    	}
	});	


	
	$('#submit').mousedown(function() {
		$(this).addClass('mousedown');
		$('body').addClass('submit_hover');
	});
	
	// disable submit button on initial submit
	$("#search-form").submit(function() {
		$("#submit").attr('disabled', 'disabled');
	});	

	$("#search-form").validate({
		invalidHandler: function(form, validator) {
			var errors = validator.numberOfInvalids();
			if (errors) {
				var message = errors == 1
					? 'Please correct the following error:\n'
					: 'Please correct the following ' + errors + ' errors.\n';
				
				var errors = "";
				
				if (validator.errorList.length > 0) {
					for (x=0;x<validator.errorList.length;x++) {
						errors += "\n\u25CF " + validator.errorList[x].message;
    	            }
    	        }
    	        
    	        // re-enable submit button if error had occured to allow for re-submission
				$("#submit").removeAttr('disabled');			
    	        
	        	alert(message + errors);
			}
			validator.focusInvalid();
			
		},
		messages: {
			crd: { required: "Please choose a credit card type" },
			amt: { required: "Please choose how much you spend monthly" },
			trm: { required: "Please choose if you carry a balance" },
			had_bankruptcy: { required: "Please choose if you have had a bankruptcy" },
			has_credit_card: { required: "Please choose if you have a credit card" },
			quality: { required: "Please choose how your credit is" },
			offer: { required: "Please choose credit or cash type your interested in" }, 
			email: {
				required: "Email address is required"
			}
		},
		onfocusout: false,
		onkeyup: false,
		onclick: false,
		errorPlacement: function(error,element) {
			return true;
		},
        submitHandler: function(form){
            //alert('submitting');
            
            var postResponse = null;
    
            $.ajax({
                type: 'POST',
                url:    '/submit',
                data: $('#search-form').serialize(),
                success: function(data){
                    //alert("data loaded: " + data);
                    postResponse = $.parseJSON(data);
                                                                    
                 },
                 async: false
            }); 
            
            if(postResponse !== null)
            {
                //alert(obj);
                
                // tracking pixel
                if(postResponse.rules.tracking_pixel !== false) {
                	//alert('Dropping tracking pixel');
                	$('body').append(postResponse.rules.tracking_pixel);
                } else {
                	//alert('No tracking pixel');
                }
                
                if(postResponse.rules.popup){
                    //alert('up');
                    var wpop = window.open(postResponse.rules.popup_url);
                    wpop.focus();
                }

                if(postResponse.rules.popunder){
                    var wpop = window.open(postResponse.rules.popunder_url, "squad");
                    wpop.blur();
                    
                    window.focus();
                }
                
                setTimeout(function() {
                	window.location.href = postResponse.rules.redirect_url; 
                	}, 1000);
                
            }               
        }
	
	});
});
