var HOUR_IN_MSEC = 1000 * 60 * 60;
var WORKING_HOUS_PER_DAY = 8;
var SUNDAY = 0, SATURDAY = 6;
var NUM_DAYS_FOR_WP = 2;
var working_hours_interval = {"start": 9, "end": 18};

var is_expedited = false;
var expedited_by = null;
var expedited_asap = false;;


var prices = {
	"homepage": 138,
	"innerpage": 68,
	"wordpress": 168,
	"expedited": 98 // per day
};
var months_map = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 
				  'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

Date.prototype.iso = function () {
    return this.getFullYear() + "-" + parseInt(this.getMonth() + 1) + "-" + this.getDate();
}

$(function() {
	$('#number_of_pages').keyup(reset_expedited);
	
	$('#number_of_pages').keyup(toggle_expedited_opts);
	$('input[name=wordpress]').click(toggle_expedited_opts);
	
	$('#number_of_pages').keyup(recalculate_price);
	$('input[name=wordpress]').click(recalculate_price);
	$('input[name=use_it]').click(recalculate_price);
	
	// Initial price calculation
	recalculate_price();
		
	function toggle_choises_box() {
	    $('.expeditedoptscontainer').toggle();
	    $(document).unbind('click', toggle_choises_box);
	}
	$('#change_exp a').live('click', function(){
		toggle_choises_box();
		setTimeout(function () {
		    $(document).bind('click', toggle_choises_box);
		});
		return false;
	});
	$('.expeditedoptscontainer a').live('click', function() {
		$('#change_exp a').remove();
		var _new = $(this).remove();
		$('#change_exp').append(_new);
		$('#expedited_hidden').attr('value', _new.html());
		
		if ($(this).hasClass('asap')) {
			//expedited_by = 'asap';
			expedited_by = this.className.replace(/.*_/, '');
			expedited_asap = true;
			is_expedited = true;
		} else if ($(this).hasClass('no')) {
			expedited_by = null;
			expedited_asap = false;
			is_expedited = false;
		} else {
			expedited_by = this.className.replace(/.*_/, '');
			is_expedited = true;
			expedited_asap = false;
		}
		recalculate_price();

		toggle_expedited_opts();
		
		return false;
	});
});
function reset_expedited() {
    is_expedited = false;
	expedited_by = null;
	expedited_asap = false;
	$('#change_exp').html('<a href="#" class="no">NO, thanks</a>');
	$('#expedited_hidden').attr('value', 'NO');
	toggle_expedited_opts();
}
function calc_est_delivery(start_date, working_hours) {
	if (working_hours < 1) {
		return null;
	}
	if (working_hours > 15000) {
		// So huge values will make the browser unresponsive
		return null;
	}
	// create date with same timestamp
	var s_date = new Date();
	s_date.setTime(start_date.getTime());
	var end_date = new Date();
	end_date.setTime(start_date.getTime());

	for (hours = 0 ; hours < working_hours; ) {
		var is_working_day = !(s_date.getDay()==SUNDAY || s_date.getDay()==SATURDAY);
		var is_working_hour = s_date.getHours() > working_hours_interval.start && 
							  s_date.getHours() < working_hours_interval.end;
		if (is_working_day && is_working_hour) {
			hours++;
			end_date.setTime(s_date.getTime());
		}
		s_date.setTime(s_date.getTime() + HOUR_IN_MSEC);
	}
	return end_date;
}

(function test_calc_est_delivery() {
	var cases = [
		{start_d: new Date(2009, 02, 21, 16, 27), hours: 20, expected: new Date(2009, 02, 25)},
		{start_d: new Date(2009, 02, 21, 16, 27), hours: 64, expected: new Date(2009, 03, 01)},
		{start_d: new Date(2009, 02, 21, 16, 27), hours: 8, expected: new Date(2009, 02, 23)}
	];
	var fine = 0;
    for (var i=0; i < cases.length; i++) {
    	var input = cases[i];
    	var actual_res = calc_est_delivery(input.start_d, input.hours);
    	
		if (
			actual_res.getFullYear() != input.expected.getFullYear() ||
			actual_res.getDate() != input.expected.getDate() ||
			actual_res.getMonth() != input.expected.getMonth()
		) {
			console.log("Falied for input: " + input.start_d.iso() + " + " + input.hours + 
				" working hours, expected " + input.expected.iso() + ", got " + actual_res.iso());
		} else {
			fine++;
		}
    }
    console.log(cases.length + " tests with " + (cases.length - fine) + " errors.");
})//();

function recalculate_price() {
	var num_pages = parseFloat($('#number_of_pages').attr('value'));
	
	if(isNaN(num_pages) || num_pages == 0){
		num_pages = 1;
	}
	$('#number_of_pages').val(num_pages);
	
	if (num_pages<5) {
		var working_hours = num_pages * WORKING_HOUS_PER_DAY;
	} else {
		var working_hours = 4 * WORKING_HOUS_PER_DAY + ((num_pages - 4) * ( WORKING_HOUS_PER_DAY / 2 ));
	}
	var has_wordpress = $('#wordpress_yes').is(':checked');
	
	var est_delivery = calc_est_delivery(new Date(), working_hours);
	// 1 home page + (N - 1) inner pages
	var price = prices.homepage + (num_pages - 1) * prices.innerpage;
	if (is_expedited) {
		// Price increseases for expideted projects
		price += expedited_by * prices.expedited;
		// Change the estimated delivery
		working_hours = working_hours - expedited_by * WORKING_HOUS_PER_DAY;
		est_delivery = calc_est_delivery(new Date(), working_hours);
	}

	if (has_wordpress) {
		working_hours += NUM_DAYS_FOR_WP * WORKING_HOUS_PER_DAY;
		est_delivery = calc_est_delivery(new Date(), working_hours);
		
		price += prices.wordpress;
	}
	
	var can_use_it_in_samples = $('#use_it_yes').is(':checked');
	
	if(can_use_it_in_samples) {
		price -= 20;
	}
	
	
	// Hidden fields -- values here go to server side scripts
	$('#price').attr('value', price);
	$('#delivery_date').attr('value', est_delivery.iso());
	
	$('.count_working_hours').html(working_hours);
	$('.count_business_days').html(Math.ceil(working_hours / WORKING_HOUS_PER_DAY));
	$('#total_price').html('$' + price);
	$('#est_delivery').html(est_delivery.getDate() + '-' + months_map[est_delivery.getMonth()]);
	
	
	
}

function toggle_expedited_opts() {
    var num_working_days = parseFloat($('#number_of_pages').attr('value'));
	if ( $('#wordpress_yes').is(':checked')) {
		num_working_days += NUM_DAYS_FOR_WP;
	}
	$('.expeditedoptscontainer').html('');
	var opts = [];
	if (expedited_by!=null) {
		opts.push('<a href="#" class="no">NO, thanks</a>');
	}
	for (var i=0; i < Math.min(num_working_days - 1, 4); i++) {
		if (expedited_asap || expedited_by!=parseInt(i + 1)) {
			opts.push('<a href="#" class="expedited_by_' + parseInt(i + 1) + '">YES, by ' + parseInt(i + 1) + ' business day</a>');
		}
	}
	if (!expedited_asap) {
		opts.push('<a href="#" class="asap expedited_by_' + parseInt(i) + '">YES, as soon as possible; get back to me!</a>');
	}
	$('.expeditedoptscontainer').html(opts.join(''));
}


function validate() {
	var f = document.getElementById('cform');
	if (f.name.value=="") {
		window.alert("Please, enter your Name.");
		f.name.focus();
		return false;
	}else if(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/.test(f.mail.value)==false) {
		window.alert("Please, enter your Email Address.");
		f.mail.focus();
		return false;
	}else if (f.comments.value=="") {
		window.alert("Please, enter your Comments, Instructions or Link to your files.");
		f.comments.focus();
		return false;
	}else {
		return true;
	}
}