// app specific javascript
var app = $.extend(true, app, {

	url: null,

	post: function(url, data, callback) {
		app.ajax('post', url, data, callback);
	},

	get: function(url, data, callback) {
		app.ajax('get', url, data, callback);
	},

	ajax: function(type, url, data, callback) {
		$.ajax({
			// first do data
			'type': type,
			'url': url,
			'data': $.extend({ajax: true, ajax_nonce: app.nonce}, data),
			'dataType': 'json',
			'success': function(response_data, code, xhr) { 
				app.nonce = response_data.nonce;
				
				if (callback) 
				{ 
					callback.call(this, response_data, code, xhr); 
				} 

				if (ajax_handlers)
				{
					ajax_handlers.local.success(response_data, code, xhr);
				}
			}
		});

	},

	init: function() {
		$('.js_reorder').click(function(e) {
			e.preventDefault();
			if (app.questions.sort != $(e.currentTarget).attr('rel'))
			{
				// reset the mroe questions bit.
				var new_sort = $(e.currentTarget).attr('rel');
				if (new_sort == 'votes')
				{
					app.questions.min = app.questions.top_count;
				} else
				{
					app.questions.min = 0;
				}
				app.questions.sort = $(e.currentTarget).attr('rel');
				$('.js_rest_questions').empty();
			}

			app.get_more_questions();

		});
		
		$('.js_morevote').click(function(e) {
			e.preventDefault();
			app.get_more_questions();
		});
		
	},
	
	get_more_questions: function()
	{
		$('.js_rest_questions_spinner').show();
		app.get(app.url + 'oursay/', {
			get_more_questions: true,
			oursay_id: app.oursay.id,
			start_at: app.questions.min,
			count: app.questions.increment,
			order: app.questions.sort
		}, function(data, code) {
			$('.js_rest_questions_spinner').hide();
			app.questions.min += app.questions.increment;
			$('.js_rest_questions').append(data.data.questions);
			
			if (data.data.is_more_questions)
			{
				$('.js_is_morequestions').show();
			} else
			{
				$('.js_is_morequestions').hide();
			}
		});
	}
});

var ajax_handlers = { local: { success: function() {} }};

$(document).ready(app.init);
