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";
	});
	
	// handle submission of chart generation code
	$("#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(),
			pt: pt,
			pr: pr
		}, function( html ) {
			$('#chart_div').prepend( html );
		});
	});
	
	// handle chart form auto-dropdown changing
	$('#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');
			
		}
	});
	
	// handle chart form auto-dropdown changing
	$('#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 ) {
		
		var targetType = 'none';
		
		// table sorting
		if ($(event.target).is('th'))
		{
			/* not ready for primetime
			// http://www.packtpub.com/article/jquery-table-manipulation-part1
			var ci = event.target.cellIndex;
			var table = $(event.target).parent().parent().parent();
			var rows = table.find('tbody > tr').get();
			rows.sort( function( a, b ) {
				var cA = $(a).children('td').eq(ci);
				var cB = $(b).children('td').eq(ci);
				var keyA;
				var keyB;
				if( $(cA).attr('sortval') != null ) {
					keyA = $(cA).attr('sortVal');
					keyB = $(cB).attr('sortVal');
				} else {
					keyA = cA.text().toUpperCase();
					keyB = cB.text().toUpperCase();
				}
				if( keyA.match(/^\d$/) && keyB.match(/^\d$/))
				{
					console.log( 'numeric match' );
					keyA = parseInt( keyA );
					keyB = parseInt( keyB );
				}
				if( keyA < keyB ) return -1;
				if( keyA > keyB ) return 1;
				return 0;
			});
			$.each( rows, function( index, row ) {
				$(table).children('tbody').append(row);
			});
			*/
		}
		// chart remove button
		else if ($(event.target).is('span.chart_remove'))
		{
			var chart_id = $(event.target).attr('id').substring(13);
			$('#chart_'+chart_id).remove();
		}
		// container and locations stuff.
		// was the event fired on a container row? 
		else if ($(event.target).is('tr.container'))
		{
			targetType = 'container';
			row = $(event.target);
		}
		//  a container cell?
		else if ($(event.target).parent().is('tr.container') && !$(event.target).is('img.edit_button'))
		{
			targetType = 'container';
			row = $(event.target).parent();
		}
		// a container cell content?
		else if ($(event.target).parent().parent().is('tr.container') && !$(event.target).is('img.edit_button'))
		{
			targetType = 'container';
			row = $(event.target).parent().parent();
		}
		// a location row?
		else if ($(event.target).is('tr.location'))
		{
			targetType = 'location';
			row = $(event.target);
		}
		// a location row cell?
		else if ($(event.target).parent().is('tr.location'))
		{
			targetType = 'location';
			row = $(event.target).parent();
		}
		
		// if so, open it!
		if (targetType != 'none' && typeof row != 'undefined')
		{
			id = row.attr('id');
			handleContainerClick(row, charid, targetType);
		}
		
		// custom name handling
		// when a custom_name span with class "custom_name" is clicked, this should pop in
		// a text editign field that will submit to a script and change the name of the item
		// in the DB
		if( $(event.target).is('img.edit_button') )
		{
			var custom_span = $(event.target).parent('span.custom_name_span');
			var active_td = custom_span.parent('td');
			var custom_name = $('span.custom_name',custom_span).text();
			
			custom_span.hide();
			
			active_td.prepend(
				'<form onsubmit="saveCustomName(); return false;">\
					<input type="text" id="custom_name" value="'+custom_name+'"/>\
					<input type="submit" value="save"/>\
				</form>'
			);
		}
	});
	$('body').keyup( function( event ) {
		if( $(event.target).is('#cpUserid') || $(event.target).is('#cpApikey') )
		{
			handleCharLoaderKeystroke();
		}
	});
	$('#cpUserid').change( function(event) {
		handleCharLoaderKeystroke();
	});
	$('#cpApikey').change( function(event) {
		handleCharLoaderKeystroke();
	});
	// change/add custom name for item/container
});
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 class="dataCellUnitPrice">UNIT PRICE</th>\
				<th class="dataCellTotalPrice">TOTAL PRICE</th>\
			</tr>\
			<tr id="loadingRow_'+cid+'"><td colspan="7"><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, pt: pt, pr: pr, sort: sortby},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 total_volume = $("total_volume",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="normal container" id="container_'+itemid+'"' : 'class="normal"')+'>\
			<td class="dataCellIcon"><img class="icon" src="'+gImagedir+icon+'.png" align="left"></td>\
			<td class="dataCellName" sortval="'+name+'">'+
				'<span id="custom_name_span_'+itemid+'" class="custom_name_span"><img width="10" height="10" src="img/edit.gif" class="edit_button"/> <span id="custom_name_'+itemid+'" class="custom_name">'+custom_name+'</span></span>'+
				((custom_name != null && custom_name != "")
				? " - "
				: '')
			+name+(contentsCount > 0 ? '<br/><span class="containerCountText">(Contains '+contentsCount+' objects)</span>' : '')+'\
			</td>\
			<td class="dataCellQuantity" sortval="'+quantity+'">'+quantity+'</td>\
			<td class="dataCellGroup" sortval="'+groupName+'">'+groupName+'</td>\
			<td class="dataCellFlag" sortval="'+flagname+'">'+flagname+'</td>\
			<td class="dataCellUnitPrice" sortval="'+avg_price+'">'+addCommas(Math.round(avg_price))+'</td>\
			<td class="dataCellTotalPrice" sortval="'+totalPrice+'">'+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;
} // }}}
