//TODO: add a 'fade out' routine for error messages and deleting elements.
//TODO: Replace parseFloat with a regex, ! 0-9 or .

var drop = $('droptarget'); //Drop container for drag & drop
var dropFx = drop.effect('background-color', {wait: false}); // wait is needed so that to toggle the effect,
var containerCount = 0; //Number of 'items' currently in the drop area

//Total cost of the war thus far
//TODO: PHP This
var totalCost = calc_amount(1);

var cssClass = new Asset.css('http://www.militarywidgets.com/cost_images/cost_Grey.css');


$$('li.options').each(function(item){
	addDragDrop(item);
});

$('item_create').onclick = function(e) {
	e = new Event(e).stop();
	itemCount++;
	add_item($('item_name').value,$('item_cost').value,itemCount);
	$('item_name').value = "";
	$('item_cost').value = "0.00";
}

function add_item(itemTitle, itemCost, itemCounter)
{
//TODO: Strip out non numerics with a regex, ^[0-9] i think
//TODO: mouse-over = cost
	//Create the new element, making sure all it's IDs have the right counter value.
	newLi = new Element('li',{'class':'options','id':'item_'+(itemCounter+1)});
	newLi.setHTML('<p><span id="dsign_item_'+(itemCounter+1)+'">$</span><span id="cost_item_'+(itemCounter+1)+'" class="cost_number">'+itemCost+'</span><br><span class="cost_name">'+itemTitle+'</span></p></li>');
	

	addDragDrop(newLi);
	newLi.injectInside('possible_items');

}

$$('img.imagepreview').each(function(item){
	//On click of the preview images, set the visual theme to that color
	item.addEvent('click',function() { 
		swapClass(item.id);
	});
});


function swapClass(newClass)
{
	cssClass.remove();
	//Load the css file for the new color class
	cssClass = new Asset.css('http://www.militarywidgets.com/cost_images/cost_'+newClass+'.css');
	$('theme').value = newClass;
}

function addDragDrop(item)
{
	//Add onmousedown events to generate a clone, start dragging, allow dropping
	item.addEvent('mousedown', function(e) {
		e = new Event(e).stop();

		//Create a copy to be 'lifted'
		var clone = this.clone()	
			.setStyles(this.getCoordinates()) // this returns an object with left/top/bottom/right, so its perfect
			.setStyles({'opacity': 0.7, 'position': 'absolute'})
			.addEvent('emptydrop', function() {
				this.remove();
				drop.removeEvents();
			}).inject(document.body);

		drop.addEvents({
			'drop': function() {
				
				if (containerCount < 4)
				{
					drop.removeEvents();
					clone.remove();
					//On drop, apply the visuals for items 'placed' inside the widget
					newEl = item.clone().addClass('placed').removeClass('options').inject(drop);	

					dropFx.start('7389AE').chain(dropFx.start.pass('ffffff', dropFx));
					//Add the close buttons and sort arrow
					new Element('div',{'events':{'click': function(){this.getParent().remove(); containerCount--;}},'class':'closebutton'}).injectTop(newEl);
					new Element('img',{'src':'http://www.militarywidgets.com/images/arrow.gif','class':'sortarrow'}).injectInside(newEl);
					//Re-initialize the sortables, because theres a new element
					new Sortables($('droptarget'),{'handles':$$('.sortarrow')});
					//Increment the total number of placed items
					containerCount++;
					//Pull the single-item cost into js
					//itemCost = parseFloat($('cost_'+newEl.id).getText());
					itemCost = parseFloat($('cost_'+newEl.id).getText().replace(/,/g,''));
					
					//Clear the $, this is counting # now, instead of measuring price
					$('dsign_'+newEl.id).setHTML("");
					//Add digit groupings, round, insert 
					$('cost_'+newEl.id).setHTML(addCommas(Math.round(totalCost/itemCost)));
					
				} else {
					drop.removeEvents();
					clone.remove();
					//TODO, error message blink red
				}
			},
			'over': function() {
				if (containerCount < 4)
				{
					dropFx.start('98B5C1');
				}
			},
			'leave': function() {
				if (containerCount < 4)
				{
					dropFx.start('ffffff');
				}
			}
		});

		var drag = clone.makeDraggable({
			droppables: [drop]
		}); // this returns the dragged element

		drag.start(e); // start the event manual
	});

}

function addCommas(nStr)
{
	//Adds digit seperators to a #
	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;
}

$('submit').addEvent('click',function(e){
	e = new Event(e).stop();
	
	$$('li.placed').each(function(item){
		//console.log("Item: "+item.id);
		
		//Grab the li with the price and name info, making sure to get the one from .options 
		var parentLi = $('possible_items').getElement('li[id='+item.id+']');
		
		var itemVal = parentLi.getElement('span.cost_number').getText();
		var itemName = parentLi.getElement('span.cost_name').getText();
		
		//console.log('Item: '+itemName+' $'+itemVal);
		new Element('input',{'type':'hidden','name':'items[]','value':item.id+'||'+itemName+'||'+itemVal}).injectInside('widget_form');
	});
	
	$('widget_form').submit();
});

function calc_amount (divisor) {
	var divisor = (divisor == null) ? 1 : divisor;
	//Basic numbers taken from costofwar.com 
	// Start Apr 17 2003 to Sept 30, 2007
	var widget_totalms = 140659200000;
	//var widget_totalms = 2387520000;
	var widget_initialdollars= 0;
	var widget_totaldollars  = 456100000000 - widget_initialdollars;
	var widget_rateperms     = widget_totaldollars / widget_totalms;

	var widget_startofwar = new Date ("Apr 17, 2003");
	var widget_curdate = new Date ();
	var widget_diff = widget_curdate - widget_startofwar;

	if (widget_diff < 0) {
		alert ("This widget uses your computers date to calculate the costs of the Iraq War. Yours must be wrong because according to your computer the war hasn't even started yet!");
	}

	// Do the actual calculations and get the amount before and after interest.
	// Note that we include the geographicscale as well.
	//curamount = (widget_initialdollars + widget_diff * widget_rateperms) * widget_geographicscale;
	
	return ((widget_rateperms * widget_diff) / divisor);
}	

function widget_update()
{
	$("totalcost_top").innerHTML = addCommas(Math.round(calc_amount()));
	$("warcost_amount").innerHTML = addCommas(Math.round(calc_amount()));
	//setTimeout('widget_update()',200);
}

setTimeout('widget_update()',200);