$(document).ready( function() {	
	$('.answer').hide();
	/* Set up placeholder text in input and textarea fields */
	insertPlaceholder( 'input:text' );
	setSupportHeight();
	setSubnavHeight();
	equalHeights('.subs .support-box');
	$("#state-affiliates ul").splitList(2, {
		'splitInto': 'rows'
	}).children('div').addClass('clearfix row');
	
	$('.addthis_toolbox').show().hover(function(){
	    $('.addthis_toolbox .hover_menu').toggle();
	});
	
	$('#publication_list > :first-child').addClass('childfirstchild');
	
	if($('#faq').length){
		//show and hide answers
		$('.question').click(function(){
			//if the answer is showing
			if($(this).next().is(':visible')){
				//collapse answer
				$(this).removeClass('expanded').next().hide();
			}
			else{
				//expand answer
				$(this).addClass('expanded').next().show();
			}
		});
	}
	
	//show and hide accurate
	if($('#calculator-form').length){
		$('#show-accurate input').change(function(){
			if($('#accurate-check').is(':checked')) {
				$('.continue').addClass('continue-right');
				$('#accurate').show();
			}
			else {
				$('.continue').removeClass('continue-right');
				$('#accurate').hide();
			}
		});
	}
	
	//add error class to labels
	if($('.donate-online').length){
		if($('#donation .error').length){
			$('#donation .error').prev("label").addClass('label-error');
			$('#donation .error').parents('fieldset').children(':first-child').addClass('label-error');
	
		}
	}
	
	//click on other input box selects other in radio option
	$('#id_amountVal').click(function(){
		$('#id_amount_5').attr('checked', 'checked');
	})
	
	//allow user to only input numbers into the calculator
	$("#calculator-form input").keydown(function(event) {
		//allow backspace, delete, and tab
		if ( event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 ) {
			//let it happen, don't do anything
		}
		else {
			//allow numbers input
			if (event.keyCode < 48 || event.keyCode > 57 && event.keyCode < 96 || event.keyCode > 105) {
				event.preventDefault();
			}
		}
	});
});

//add comma's to numbers
function comma(nStr){
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

//calculate donation
function calculate(){
	//form is visible
	if($('#calculator-form').is(':visible')){
		$('#calculator-form').hide();
		$('.continue').removeClass('continue-right').addClass('continue-left');
		//get values, remove $ and any other unwanted text
	    var amount = parseInt($('#amount').val().replace(/\D/g,""));
	    var cost = parseInt($('#cost').val().replace(/\D/g,""));
	    var tax = parseFloat($('#tax').val());
	    var state = parseInt($('#state').val().replace(/\D/g,""))/100;
	    var gains =  parseInt($('#gains').val())/100;
	    var capitalTax = 0.15;
	    //set default values if amount or cost aren't set
	    if(amount == '' || isNaN(amount)){
	    	amount = 0;
	    }
	    if(cost == '' || isNaN(cost)){
	    	cost = 0;
	    }
	    if(state == '' || isNaN(state)){
	    	state = 0;
	    }
	    if(gains == '' || isNaN(gains)){
	    	gains = 0;
	    }
	    $("#input-1").text(comma(amount.toFixed(2)));
	    $("#input-2").text(comma(cost.toFixed(2)));
	    $("#input-3").text(comma(tax*100));
	    //if state tax is set, add state tax to tax
	    if(state != 0){
	    	//show state results
	    	$("#state-results").show();
	    	$("#input-4").text(state*100);
	    	tax = tax + state;
	    }
	    if(gains != 0){
	    	capitalTax = capitalTax + gains
	    	$("#input-5").text(gains*100);
	    }
	    //gift
	    $("#result-1").text(comma(amount.toFixed(2)));
	    $("#result-2").text(comma(amount.toFixed(2)));
	    //income
	    var income = amount*tax;
	    $("#result-3").text(comma(income.toFixed(2)));
	    $("#result-4").text(comma(income.toFixed(2)));
	    //capital
	    var capital = 0;
	    //if tax is 25% or higher, calculate capital gains tax
	    if(tax > 0.24){
	    	capital = (amount-cost)*capitalTax;
	    }
	    //state has capital gains tax and its below 25%
	    else if(gains != 0){
    		capital = (amount-cost)*gains;
		}
	    $("#result-5").text(comma(capital.toFixed(2)));
    	$("#result-11").text(comma(capital.toFixed(2)));
	    $("#result-6").text("None");
	    //total
	    $("#result-7").text(comma((income + capital).toFixed(2)));
	    $("#result-8").text(comma(income.toFixed(2)));
	    //net
	    $("#result-9").text(comma((amount - (income + capital)).toFixed(2)));
	    $("#result-10").text(comma((amount - income).toFixed(2)));
	    //update continue button
		$('.continue a').html('Start Over &raquo;');
		//show results
		$('#calculator-results').show();
	}
	//results is visible / start over click
	else{
		//hide results
		$('#calculator-results').hide();
		//hide state results
    	$("#state-results").hide();
		//change continue text
		$('.continue a').html('Calculate &raquo;');
		//remove continue position classes
		$('.continue').removeClass('continue-right').removeClass('continue-left');
		//hide accurate fields
		$('#accurate').hide();
		//uncheck the show accurate check box
		$('#accurate-check').attr('checked', false);
		//show accurate text
		$('#show-accurate').show();
		//reset form values
		$('#amount').val("$");
		$('#cost').val("$");
		$('#tax').val("0.35");
		$('#state').val("");
		$('#gains').val("");
		//show calculator form
		$('#calculator-form').show();
		//scroll up
		document.getElementById('donate-form').scrollIntoView();
	}
}

/* See if the browser understands the placeholder attribute */
function testPlaceholder() {
	var i = document.createElement('input');
	return 'placeholder' in i;
}

/* Insert placeholder text into inputs */
function insertPlaceholder( el ) {
	var hasPlaceholder = testPlaceholder();
	if( hasPlaceholder ) {
		return;
	} else {
		$( el ).each( function() {
			var inputValue = $(this).attr('value');
			var placeholder = $(this).attr('placeholder');
			if(inputValue != placeholder) {
				$(this).val( placeholder );
				inputValue = $(this).val();
			}
			
			$(this).focus( function() {
				if( inputValue == placeholder ) {
					$(this).val( '' );
				}
				inputValue = $(this).val();
			});
			
			$(this).blur( function() {
				inputValue = $(this).val();
				if( inputValue == placeholder || inputValue == '' ) {
					$(this).val( placeholder );
				} else {
					$(this).val( inputValue );
				}
				inputValue = $(this).val();
			});
			
		});
	}
}



/* Equalize the height of the intro support boxes */
function setSupportHeight() {
	var supportHeight = $('#support-boxes').height();
	$('.support-box').height(supportHeight-38);
}

/* Calculate intro div height on landing page and set the nav to match that height */
function setSubnavHeight() {
	var introHeight = $('.landing #intro').height();
	$('.landing #sub-nav').height(introHeight-34);
}

/* Equalize the height of the support boxes in the article*/
function equalHeights(box) {
	var currentTallest = 0;
	$(box).each(function(){
		if ($(this).outerHeight() > currentTallest) { currentTallest = $(this).outerHeight(); }
	});

	$(box).each(function(){
		
		if ($(this).outerHeight() !== currentTallest) { 
			var newHeight = $(this).height() + (currentTallest - $(this).outerHeight());
			$(this).height(newHeight);
			
		}
	});  
};



/* jQuery split a list into multiple rows or columns
* version 3.0 (02/10/2010)
* developed by David Zhou, Matt Billings, David Durst, and Chuck Harmston
* take an unordered list and split it into multiple divs.
* you can float the divs so it looks like multiple columns/lists.
* 
* usage: 
*    $(".dropdown ul").splitList(3);
*    $(".dropdown ul").splitList(3, { wrapClass: "div_class_name" });
*    $(".dropdown ul").splitList(3, { splitInto: "div_class_name" });
* 
* If option splitInto is set to 'cols' (as it is by default), it will
* split into the specified number of columns. Otherwise, it will split
* into rows, with the specified number of <li>s per row.
* 
*/

$.fn.splitList = function(n, options){
	settings = $.extend({
		wrapClass: false,
		splitInto: 'cols'
	}, options);
	return this.each(function(){
		var intoCols = (settings['splitInto'] == 'cols');
		$lis = jQuery(this).find("> li");		
		$inc = intoCols ? parseInt(($lis.length/n) + ($lis.length % n > 0 )) : n;
		var w = '<div' + (settings['wrapClass'] ? ' class="' + settings['wrapClass'] + '"' : '' ) + '></div>';
		for(var i=0; i<(intoCols ? n : Math.ceil($lis.length/n)); i++)
			$lis.slice($inc*i, $inc*(i+1)).wrapAll(w);
	});
};
