var open_containers = new Array();
var keystrokeTimer = null;

var loadedUserid = null;
var loadedApikey = null;

function isEmpty( val )
{
	return val == null || val == "";
}

$(document).ready(function() {
	loadedApikey = null;
	loadedUserid = null;

	$('#cpApikey').val('');
	$('#cpUserid').val('');

	// create list of locations in the table
	$("#assetTable tbody tr").each(function(i) {
		if( this.id != null && this.id != "" )
			open_containers[ this.id ] = "null";
	});
	
	$("#charts_form").submit( function() {
		// build query for chart insert ajax script
		$.get('ajax/insert_chart.php',{
			groupby: $('#f_groupby').val(),
			limit_category: $('#f_limit_category').val(),
			limit_category_name: $('#f_limit_category_'+$('#f_limit_category').val()).text(),
			limit_group: $('#f_limit_group').val(),
			limit_group_name: $('#f_limit_group_'+$('#f_limit_group').val()).text(),
			sb: !isEmpty($('#f_sb').attr('checked')) ? 1 : '',
			charid: $('#f_charid').val()
		}, function( html ) {
			$('#chart_div').prepend( html );
		});
	});
	
	$('#f_limit_category').change( function() {
		var cat_id = $('#f_limit_category').val();
		var groups = chart_groups[ cat_id ];
		$('#f_limit_group').empty();
		$('#f_limit_group').append('<option value="">All Sub-categories</option>');
		for( var i in groups )
		{
			$('#f_limit_group').append('<option value="'+i+'" id="f_limit_group_'+i+'">'+groups[i]+'</option>');
		}
		$('#f_limit_group > option:first').attr('selected','selected');
		// make sure the 'summarize' select box has category removed or unselected
		if( !isEmpty($('#f_limit_category').val()) )
		{
			if( $('#f_groupby').val() == 'category' )
				$('#f_groupby > option[value="group"]').attr('selected','selected');
		} else {
			$('#f_groupby > option[value="category"]').attr('selected','selected');
			
		}
	});
	
	$('#f_limit_group').change( function() {
		if( !isEmpty( $('#f_limit_group').val() ) ) {
			if( $('#f_groupby').val() == 'category' ||  $('#f_groupby').val() == 'group')
				$('#f_groupby > option[value="type"]').attr('selected','selected');
		} else {
			$('#f_groupby > option[value="group"]').attr('selected','selected');
		}
	});
	
	$('body').click( function( event ) {
		if( $(event.target).is('tr.container') || $(event.target).parent().is('tr.container') ) {
			if( $(event.target).is('tr.container') )
				row = $(event.target);
			else if( $(event.target).parent().is('tr.container') )
				row = $(event.target).parent();
			
			id = row.attr('id');
			
			handleContainerClick( row, charid, 'container' );
		}
		if( $(event.target).is('tr.location') || $(event.target).parent().is('tr.location') ) {
			if( $(event.target).is('tr.location') )
				row = $(event.target);
			else if( $(event.target).parent().is('tr.location') )
				row = $(event.target).parent();
			
			handleContainerClick( row, charid, 'location' );
		}
		if( $(event.target).is( 'span.chart_remove' ) )
		{
			var chart_id = $(event.target).attr('id').substring(13);
			$('#chart_'+chart_id).remove();
		}
	});
	$('body').keyup( function( event ) {
		if( $(event.target).is('#cpUserid') || $(event.target).is('#cpApikey') )
		{
			handleCharLoaderKeystroke();
		}
	});
	$('#cpUserid').change( function(event) {
		handleCharLoaderKeystroke();
	});
	$('#cpApikey').change( function(event) {
		handleCharLoaderKeystroke();
	});
});
function handleCharLoaderKeystroke() {
	clearTimeout( keystrokeTimer );
	var userid = $.trim($('#cpUserid').val());
	var apikey = $.trim($('#cpApikey').val());
	if( userid == null || userid == '' ||
		apikey == null || apikey == '' ||
		(userid == loadedUserid && apikey == loadedApikey ) )
	{
		return;
	}
	loadedUserid = userid;
	loadedApikey = apikey;
	keystrokeTimer = setTimeout('updateCharPicker("'+userid+'","'+apikey+'")', 300 );
}
function updateCharPicker( userid, apikey ) {
	$.post( 'ajax/chars.php',{userID: userid, apiKey: apikey},function(xml) {
		$('#charPicker').empty();
		var error = $("error",xml).text();
		if( error == 1 )
		{
			$('#charPicker').append('<option id="placeholderOpt">Invalid API Information</option>');
			return;
		}
		$("char",xml).each( function(id) {
			var char = $("char",xml).get(id);
			var id = $("id",char).text();
			var name = $("name",char).text();
			$('#charPicker').append('<option value="'+id+'">'+name+'</option>');
		});
		$('#placeholderOpt').remove();
	});
}
function handleContainerClick( row, charid, type )
{
	id = row.attr('id');
	
	if( open_containers[ id ] == null || open_containers[ id ] == "null" ) {
		if( type == 'location' )
			cid = id.substring(4);
		else
			cid = id.substring(10);
		row.after('<tr class="subTableRow">\
			<td colspan="'+(type=='location' ? 5 : 7)+'">\
			<table width="100%" id="'+cid+'_table" class="containerTable">\
			<thead>\
			<tr>\
				<th colspan="2">NAME</th>\
				<th>QTY</th>\
				<th>GROUP</th>\
				<th>LOC</th>\
				<th>UNIT PRICE</th>\
				<th>TOTAL PRICE</th>\
			</tr>\
			<tr id="loadingRow_'+cid+'"><td><img src="img/loading.gif"/>&nbsp;&nbsp;LOADING</td></tr>\
			</thead>\
			<tbody>\
			</tbody>\
			</table>\
			</td></tr>');
		// load table contents
		LoadContainerTable( cid, charid, type == 'location' ? true : false );
		open_containers[ id ] = "open";
	} else if (open_containers[ id ] == "closed" ) {
		row.next().show();
		open_containers[ id ] = "open";
	} else {
		row.next().hide();
		open_containers[ id ] = "closed";
	}
}
// 
function LoadContainerTable( cid, charid, isLocation ) {
	$.post("ajax/container.php",{cid: cid, charid: charid, isLocation: isLocation},function(xml) {
		createContainerTable( xml, cid );
	});
}
function createContainerTable( xml, cid ) {
	$("item", xml).each( function(id) {
		var item = $("item",xml).get(id);
		var name = $("typename",item).text();
		var custom_name = $("custom_name",item).text();
		var typeid = $("typeid",item).text();
		var itemid = $("itemID",item).text();
		var quantity = $("quantity",item).text();
		var avg_price = $("avg_price",item).text();
		var icon = $("icon",item).text();
		var flagname = $("flagName",item).text();
		var contentsCount = $("contentsCount",item).text();
		var contentsPrice = $("contentsPrice",item).text();
		var groupName = $("groupName",item).text();
		
		if( contentsPrice == null || contentsPrice == '' )
			totalPrice = quantity * avg_price;
		else
			totalPrice = (quantity * avg_price) + parseFloat(contentsPrice);
		
		t = $('#'+cid+'_table tbody')
		t.append('<tr'+(contentsCount > 0 ? ' class="container" id="container_'+itemid+'"' : '')+'>\
			<td class="dataCellIcon"><img class="icon" src="/eveimagestest/32/'+icon+'.png" align="left"></td>\
			<td class="dataCellName">'+((custom_name != null && custom_name != "") ? custom_name + " ("+name+")" : name)+'\
			'+(contentsCount > 0 ? '<br/><span class="containerCountText">(Contains '+contentsCount+' objects)</span>' : '')+'\
			</td>\
			<td class="dataCellQuantity">'+quantity+'</td>\
			<td class="dataCellGroup">'+groupName+'</td>\
			<td class="dataCellFlag">'+flagname+'</td>\
			<td class="dataCellUnitPrice">'+addCommas(Math.round(avg_price))+'</td>\
			<td class="dataCellTotalPrice">'+addCommas(Math.round(totalPrice))+'</td>\
		</tr>');
		$('#loadingRow_'+cid).remove();
	});
}
function addCommas(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;
} // }}}
