// Calculator
//static variables
var total;
var rackspace;
var exchange;
var intervalID;
var CALC_TOP = 281; //Pixels on top slider
var CALC_BOT = 240; //Pixels on bot slider
var START_TOTAL = 50;
var START_HEX = 5;


var rackspace_price = 2;
var exchange_price = 10;

//jQuery objects
var $rackspace_boxes;
var	$exchange_boxes;
var	$tophandle;
var	$bottomhandle;

function update() {
	$rackspace_boxes = $("#rackspace_boxes");
	$exchange_boxes = $("#exchange_boxes");
	$tophandle = $("#tophandle");
	$bottomhandle = $("#bottomhandle");
	
	total = Math.max(2,Math.round(parseInt($tophandle.css('left'), 10) / (CALC_TOP/100)));
	bot = parseInt($bottomhandle.css('left'), 10);//bottom handle left length
	
	//calc ratios
	ratio = CALC_BOT/total; //pixels per mailbox
	exchange = Math.max(1,Math.round(bot/ratio));
	exchange = exchange < total ? exchange : exchange-1;
	rackspace = Math.max(1,total - exchange);
	
	//update text
	$tophandle.text(total);
	$rackspace_boxes.html(rackspace);
	$exchange_boxes.html(exchange);

    var exchange_total = total * exchange_price;
    var combine_total  = (exchange * exchange_price) + (rackspace * rackspace_price);
    var savings_total  = rackspace * (exchange_price - rackspace_price);

	$("#exchange_total").text("$" + exchange_total.toFixed(2));
	$("#combine_total" ).text("$" + combine_total.toFixed(2));
	$("#savings_total" ).text("$" + savings_total.toFixed(2));
}

$(document).ready(function(){
	$rackspace_boxes = $("#rackspace_boxes");
	$exchange_boxes = $("#exchange_boxes");
	$tophandle = $("#tophandle");
	$bottomhandle = $("#bottomhandle");
	
	$tophandle.draggable({
		axis: 'x',
		containment: 'parent',
		grid: [1,1],
		drag: function(event, ui) {
			$(this).css("background-position", "0px -26px");
			update();
		},
		stop: function(event, ui) {
			$(this).css("background-position", "0px 0px");
			update();
		}
	});
	
	$tophandle.hover(function(){
		$(this).css("background-position", "0px -26px");
	}, function(){
		$(this).css("background-position", "0px 0px");
	});
	
	$bottomhandle.hover(function(){
		$(this).css("background-position", "0px -78px");
	}, function(){
		$(this).css("background-position", "0px -52px");
	});
	
	$bottomhandle.draggable({
		axis: 'x',
		containment: 'parent',
		grid: [1,1],
		drag: function(event, ui) {
			$(this).css("background-position", "0px -78px");
			update();
		},
		stop: function(event, ui) {
			$(this).css("background-position", "0px -52px");
			update();
		}
	});
	
	//animate on load
	intervalID = setInterval("update();", 100);
	total_start = START_TOTAL*(CALC_TOP/100);
	$tophandle.animate({left:total_start+"px"}, 600, function(){
		bot_start = (START_HEX*CALC_BOT)/START_TOTAL;
		$bottomhandle.animate({left:bot_start+"px"}, 1200, function(){
			clearInterval(intervalID);
		});
	});
	
	$('#calcButton').click(function(){
		if( rackspace > 0 && exchange > 0 ) {
			window.location = CFG_SIGNUP_PATH+'combined/rax:'+rackspace+'/hex:'+exchange;
		}
		return false;
	});
});

