$(function(){

	// Checkboxes in table rows
	$('td input[type=checkbox]').click(
		function() {
			if ($(this).attr('checked')) {
				$(this).parents('tr').addClass('checked');
			}
			else {
				$(this).parents('tr').removeClass('checked');
			}
		}
	);
	
	// Checkboxes in list items
	$('li input[type=checkbox]').click(
		function() {
			if ($(this).attr('checked')) {
				$(this).parents('li').addClass('checked');
			}
			else {
				$(this).parents('li').removeClass('checked');
			}
		}
	);
	
	// Focus on login
	if ($('#username').length) {
		$('#username').focus();
	}
	
	// Init drag interface
	//rttrStable.init();

});

// RTTR Stable Manager
var rttrStable = {

	activeHorses: new Array(),
	benchHorses: new Array(),
	isEngaged: false,
	curItem: undefined,
	targetItem: undefined,
	targetGroup: undefined,
	interval: undefined,
	xDiff: 0,
	yDiff: 0,
	
	init: function(){
		
		// Abort mission if there isn't the right info
		if ($('.active-horses').length + $('.benched-horses').length < 2)
		{
			return false;
		}
		
		// Build arrays and setup handlers
		$('.stable-block.active-horses li').each(
			function(i, el){
				rttrStable.activeHorses[i] = rttrStable.getHorseId(this);
				$(this).addClass('draggable').mousedown(rttrStable.engage).mouseout(rttrStable.clearTarget);
			}
		);
		$('.stable-block.benched-horses li').each(
			function(i, el){
				rttrStable.benchHorses[i] = rttrStable.getHorseId(this);
				$(this).addClass('draggable').mousedown(rttrStable.engage).mouseout(rttrStable.clearTarget);
			}
		);
		// Disengage on mouseup
		$(document).mouseup(rttrStable.disengage);
	},
	
	engage: function(e){
		rttrStable.isEngaged = true;
		rttrStable.curItem = rttrStable.getHorseId(this);
		rttrStable.targetGroup = '.benched-horses';
		if ($.inArray(rttrStable.curItem, rttrStable.benchHorses) > -1)
		{
			rttrStable.targetGroup = '.active-horses';
		}
		
		// Give a hook for styling the engaged element
		$(this).addClass('engaged');
		
		// Clone the element and fix to cursor
		$('body').css('cursor', 'move').append(
			$(this).clone().attr('id', 'rttrStableCurItem')
		);
		$(document).mousemove(rttrStable.mousemove);
		rttrStable.xDiff = e.clientX - $(this).offset().left;
		rttrStable.yDiff = e.clientY - $(this).offset().top;
		
		document.onselectstart = function(){ return false; };
		return false;
	},
	
	disengage: function(e){
		rttrStable.isEngaged = false;
	
		// Perform swap if there is a target
		if (rttrStable.targetItem)
		{
			rttrStable.swap(rttrStable.curItem, rttrStable.targetItem);
		}
		
		rttrStable.targetItem = undefined;
		rttrStable.curItem = undefined;
		
		// Set animation parameters
		var animParams = {opacity: 0};
		if ($('li.draggable.target').length == 1)
		{
			var target = $('li.draggable.target').offset();
			animParams.left = target.left +"px";
			animParams.top = target.top +"px";
		}
		
		// Remove any style hooks or affordance elements
		$('li.engaged').removeClass('engaged');
		$('li.draggable.target').removeClass('target');
		$('#rttrStableCurItem').animate(
			animParams,
			300,
			'linear',
			function(){
				$(this).remove();
			}
		);
		$('body').css('cursor', 'auto');
		
		document.onselectstart = function(){ return true; };
	},
	
	mousemove: function(e)
	{
		if (rttrStable.isEngaged)
		{
			// Move the target element
			var posX = parseInt(e.clientX - rttrStable.xDiff) +"px";
			var posY = parseInt(e.clientY - rttrStable.yDiff) +"px";
			$('#rttrStableCurItem').css({left: posX, top: posY});
			
			// Highlight hovers
			$(rttrStable.targetGroup +" li").each(
				function (i, el)
				{
					if (rttrStable.isHovered(e, el))
					{
						$(this).addClass('target');
						rttrStable.targetItem = rttrStable.getHorseId(this);
					}
					else
					{
						$(this).removeClass('target');
						if ($('li.target', rttrStable.targetGroup).length < 1)
						{
							rttrStable.targetItem = undefined;
						}
					}
				}
			);
		}
	},
	
	getHorseId: function(el){
		return $(el).attr('id').replace('horse_', '');
	},
	
	getHorseName: function(el){
		return $(el).text().substr(3);
	},
	
	swap: function(horse1, horse2){
		// TODO: This is whack right now. Need to rebuild arrays first, then try ajax, then redraw
		
		// Redraw html
		horse1html = $("#horse_"+ horse2).html();
		horse2html = $("#horse_"+ horse1).html();
		$("#horse_"+ horse1).attr('id', 'xhorse_'+ horse2).html(horse1html);
		$("#horse_"+ horse2).attr('id', 'horse_'+ horse1).html(horse2html);
		$("#xhorse_"+ horse2).attr('id', 'horse_'+ horse2);
		
		// Rebuild Arrays and numbering
		$('.stable-block.active-horses li').each(
			function(i, el){
				rttrStable.activeHorses[i] = rttrStable.getHorseId(this);
				$(this).html(i + 1 + $(this).html().substr(1));
			}
		);
		$('.stable-block.benched-horses li').each(
			function(i, el){
				rttrStable.benchHorses[i] = rttrStable.getHorseId(this);
				$(this).html(i + 1 + $(this).html().substr(1));
			}
		);
		
		// Try ajax call to update horses in db
		var uidHash = $('div.active-horses').attr('id').substr(4);
		$.ajax(
			{
				async: false,
				type: 'post',
				data: {active_horse: rttrStable.activeHorses, uid: uidHash, 'change-ah': 'Activate Checked Horses'},
				url: '/G=83/game/change_active_horses_validate.phtml',
				success: rttrStable.updateSuccess,
				error: rttrStable.updateError
			}
		);
	},
	
	isHovered: function(e, el){
		return (e.clientY + $(document).scrollTop() > $(el).offset().top && e.clientY + $(document).scrollTop() < $(el).offset().top + $(el).height())
		&&
		(e.clientX + $(document).scrollLeft() > $(el).offset().left && e.clientX + $(document).scrollLeft() < $(el).offset().left + $(el).width());
	},
	
	updateError: function(XMLHttpRequest, textStatus, errorThrown){
		alert('ERROR: '+ errorThrown);
		location.href = location.href;
	},
	
	updateSuccess: function(data, textStatus){
		alert('Active horses updated.');
	}
	
}

/* End of file */