$(document).ready(function(){
	if ($("#infinite").size()>0) {
		
		var top_scroller = $("#infinite .scrollable").scrollable({
			clickable: false,
			hoverClass: "yellow_box",
	        size: 5,
			api: true
		});

		// Seek to the current selected element in the top scroller bar.
		var selected_index = $("#infinite li").index($("#infinite .selected"));
		top_scroller.seekTo(selected_index-2);
	}

	// Event Delegation
	$('.tags').focus(function() {
		el = $(this);
		if(el.attr('bound')) { // Check if the element is already bound
			return;
		}

		craption.tags_auto_complete(el);
	});
});

var craption = new function() {
	o = this; // Name space internally
	o.tags = [];
	o.modal = null;
	o.scroll_selected = null;

	o.set_tags = function(a) {
		o.tags = a;
	}
	// Scroller settings
	o.scroll_set = {
		inc: 147, // how far to move the scroll window each direction
		panel_current: 0,
		panel_total: 0,
		btn_left: null, 
		btn_right: null,
		container: null
	}

	/*
		 The main init for the public craptions
		 Move the scroller to the correct position
	*/
	o.main_init = function(panel_current, panel_total) {
		o.scroll_set.panel_current = panel_current * 1; // Which Panel to start on
		o.scroll_set.panel_total = panel_total * 1; // How many panels
	
		// Store the elements and, if it's at the start, hide the start button
		$(function() {
			o.scroll_set.btn_left = $(".PastCraptionsGroup .Nav4 .arrowLeft");
			o.scroll_set.btn_right = $(".PastCraptionsGroup .Nav4 .arrowRight");
			o.scroll_set.container = $('#ItemsListContainer');
			
			if(o.scroll_set.panel_current == 0)
				o.scroll_set.btn_left.css("visibility", "hidden");

			if(o.scroll_set.panel_current == o.scroll_set.panel_total - 1)
				o.scroll_set.btn_right.css("visibility", "hidden");

			// If we need to scroll to another panel
//			if(o.scroll_set.panel_current > 0)
//				o.scroll_set.container.animate({"left": "-=" + (o.scroll_set.panel_current * o.scroll_set.inc) + "px"}, "slow");

		});
	}

	// Scroll the crap	
	o.scroll_right = function() {
		o.scroll_set.container.animate({"left": "-=" +  o.scroll_set.inc + "px"}, "normal");
		o.scroll_set.btn_left.css("visibility", "visible");
		if(++o.scroll_set.panel_current == o.scroll_set.panel_total - 1)
			o.scroll_set.btn_right.css("visibility", "hidden");
	}

	o.scroll_left = function() {
		o.scroll_set.container.animate({"left": "+=" +  o.scroll_set.inc + "px"}, "normal");
		o.scroll_set.btn_right.css("visibility", "visible");
		if(--o.scroll_set.panel_current == 0)
			o.scroll_set.btn_left.css("visibility", "hidden");
	}

	o.show_modal = function(text, offset) {
		// Create the modal if it doesn't exist
		if(!o.modal)
		{
			o.modal = $('<div></div>');
			var css = 
			{
				display: 'none',
				position: 'absolute',
				zIndex: 1001,
				left: '40%',
				background: '#eee',
				border: '#00f solid 1px',
				color: '#00f',
				fontWeight: 'bold',
				padding: '20px'
			}
			o.modal.css(css);
			o.modal.appendTo('body');
		}
		var window_center = $(window).scrollTop() + ($(window).height() / 2);
		var max_width = $('body').width();

		var css = 
		{
			top: offset.top,
			left: offset.left
		}
		o.modal.css(css); // Position it at the top
		o.modal.html(text);
		o.modal.slideDown('fast', function()
		{
			o.modal.fadeOut(2000);
		});
		
		
	}
	
	// Updates the craption tags
	o.submit_tags = function(e_form) {
		var options =
		{
			success: function(data)
			{
				o.submit_tags_done(data, e_form);
			},
			dataType: 'json'
		};
		
		$(e_form).ajaxSubmit(options);
		return false;
	}
	o.submit_tags_done = function(data, e_form) {
		o.show_modal('The tags have been updated', $(e_form).offset());
		o.set_tags(data);
		$('.tags').removeAttr('bound'); // unbind all tags 
	}
	
	o.tags_auto_complete = function(el)
	{
		var options =
		{
			minChars: 0,
			width: 310,
			max: 30,
			matchContains: true,
			formatItem: function(item) {return item.name; }
		};
		el.attr('bound', 'true'); // Bind it
		el.autocomplete(o.tags, options).result( o.ac_result_done );
		el.click();
	}

	// Save the tag id in the hidden column
	o.ac_result_done = function(event, item)
	{
		$('#'+event.target.id+'_id').val(item.tag_id);
	}
	
	o.rate = function(el, craption_id, score, contest_id, is_league)
	{
		// Check if the user is logged in to rate
		if(!user.id) {
			login_popup('Please login (or register) to vote for this craption.');
			return false;
		}


		var url = '/craptions/a_score.php';
		var data = 
		{
			craption_id: craption_id,
			contest_id: contest_id,
			score: score
		};

		$.getJSON(url, data, function(data) { o.rate_done(data, el, is_league); });
	}

	o.rate_done = function(data, el, is_league)
	{
		if(data.error)
		{
			alert(data.message);
			return false;
		}
		if (typeof is_league!="undefined") { window.location.reload(); return; }

		el = $("#craption_"+data.craption_id); // Get the parent element


		if(data.scored*1 < 0 && data.down_votes_remain >= 0)
		{
				var css_info = el.position();
				css_info.top;
				css_info.left += 60;
				css_info.display = 'block';
				$('#tooltip')
					.css(css_info)
					.html(data.down_votes_remain+' down votes remain')
					.fadeTo(2000, 1)
					.fadeOut('slow')
				;
		}

		el.addClass('disabled')
			.find('div') // Get the rate buttons within the elemnt to disable them.
				.unbind()
				.attr('onclick', '')
		;

		// Determine wheather or not to hilight the thumb up or thumb down.
		if(data.scored == 1) {
			el.find(".thumb_up .bg").addClass('selected');
		} else {
			el.find(".thumb_down .bg").addClass('selected');
		}

		el.find('.votes').html(data.score); // Update the score
	}
	
	o.show_craption_image = function() {
		$('#craption_image_helper').show();
		$.scrollTo(
			"#craption_image_helper",
			{
				duration: 800,
				easing: 'easeOutBounce',
				offset: 0
			}
		);

	}
}