// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
$(function(){
	$("textarea#post_ingredients").wysiwyg();
	$("textarea#post_description").wysiwyg();
	$("textarea#review_body").wysiwyg();
	$("input#post_sell_on").datepicker({  
		duration: '',  
		showTime: true,  
		constrainInput: false,  
		stepMinutes: 1,  
		stepHours: 1,  
		altTimeField: '',  
		time24h: true
	});
		
	$('#defaultCountdown').countdown({
		until: next_deal(),
		layout: determine_date_format(next_deal())
	});
	
	$('#qty-box').blur(function(){
		if(isNaN(parseInt(this.value))){
			$(this).val("1");
		}else if(this.value.match(/[^\d]/g)){
			$(this).val(this.value.replace(/[^\d]/g,''));
		}
	});
	
	$('#up_arrow').click(function(){
		quantity_input = $('#qty-box')
		quantity = parseInt(quantity_input.val());
		quantity = quantity + 1;
		quantity_input.val(quantity)
	});
	
	$('#down_arrow').click(function(){
		quantity_input = $('#qty-box')
		quantity = parseInt(quantity_input.val());
		if(quantity > 1){
			quantity = quantity - 1;
			quantity_input.val(quantity)
		}
	});
	
	$('#how').click(function(e){
		e.preventDefault();
		$("how_best_price_determined").modal();
	});
});

function addDays(myDate,days) {
	return new Date(myDate.getTime() + days*24*60*60*1000);
}

function next_deal(){
	countdown = new Date();
	year = (countdown.getYear() < 1900) ? countdown.getYear()+1900 : countdown.getYear()
	if((countdown.getDay() > 5) || (countdown.getDay() == 5 && countdown.getHours() > 21)){
		countdown = addDays(countdown, (8-countdown.getDay()));
	}else if(countdown.getHours() > 21){
		countdown = addDays(countdown, 1);
	}else{
		countdown = addDays(countdown, 0);
	}
	countdown = new Date(year, countdown.getMonth(), countdown.getDate(), 21, 0, 0, 0);
	return countdown;
}

function determine_date_format(myDate){
	if(((myDate - new Date())/1000/60/60/24) >= 1){
		return '{dn} {dl}, {hn} {hl} and {mn} {ml}'
	}else{
		return '{hn} {hl}, {mn} {ml} and {sn} {sl}'
	}
}