var DEBUG = true;
var EFFECT_DELAY = 2000;
var MONTHS = ['Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro'];
var MONTHS_ABBR = [];

for(var i in MONTHS) {
	MONTHS_ABBR.push(MONTHS[i].substr(0,3));
}

$.datePicker.setLanguageStrings(
	['Domingo', 'Segunda-feira', 'Terça-feira', 'Quarta-feira', 'Quinta-feira', 'Sexta-feira', 'Sábado'],
	MONTHS,
	{p:'Anterior', n:'Próximo', c:'Fechar', b:'Escolher data'}
);

$.datePicker.setDateFormat('dmy', '/');

$(function(){
	var controller = $('body').attr('id');
	var action = $('#page').attr('className');
	$('body').addClass('has-js');
	$('input:first').each(function(){
		this.focus();
	});

	$('input.date-picker').datePicker({startDate:'01/01/1990'});
	$('#schedule_repeats_forever').click(function(){
		if(this.checked) {
			$('#schedule_formatted_repeat_until').attr('disabled', 'disabled');
		} else {
			$('#schedule_formatted_repeat_until').removeAttr('disabled');
		}
	});

	if($('#schedule_repeats_forever').is(':checked')) {
		$('#schedule_formatted_repeat_until').attr('disabled', 'disabled');
	}

	$('#schedule_raw_amount, #operation_raw_amount').blur(function(){
		if ($('input[@id*=flow_out]:radio').is(':checked') || $('input[@id*=flow_in]:radio').is(':checked')) {
			return;
		}
		
		if (this.value.match(/^\+/)) {
			$('input[@id*=flow_in]:radio').each(function(){
				this.checked = true;
			});
		} else {
			$('input[@id*=flow_out]:radio').each(function(){
				this.checked = true;
			});
		}
	});

	if($('#schedule_repeats_forever').is(':checked')) {
		$('#schedule_formatted_repeat_until').attr('disabled', 'disabled');
	}
	
	var ad = ads('super');
	if (ad) {
		$('div.adsense-top').html(ad);
	}
	$('div.adsense-top').removeClass('hidden');
		
	try {
		if (Spesa[controller].init != undefined) {
			Spesa[controller].init.call(null);
		}
		Spesa[controller][action].call(null);
	} catch (e) {
		debug('Init', 'No init function declared [' + controller + ', ' + action + '].', e);
	}

	$('.error-list').append('<a href="javascript:;" class="close" onclick="Spesa.utils.close(\'.error-list\');">Fechar</a>');

	$('.notice, .warning, .error, .error-list, .info').not('.skip').fadeIn(EFFECT_DELAY);

	setTimeout(function(){
		$('.notice').fadeOut(EFFECT_DELAY, function(){
			$(this).remove();
		});
	}, 15000);
});

function debug(name, value, e)
{
	try {
		if (DEBUG) {
			if (value == undefined) {
				console.debug(name);
			} else {
				console.debug(name, value);
			}

			if (e) {
				console.debug(e.message);
			}
		}
	} catch (e) {
		null;
	}
}

var Spesa = {} || Spesa;
Spesa.operations = {} || Spesa.operations;
Spesa.account = {} || Spesa.account;
Spesa.utils = {} || Spesa.utils;
Spesa.schedules = {} || Spesa.schedules;
Spesa.overview = {} || Spesa.overview;

Spesa.utils.close = function(expr)
{
	$(expr).fadeOut(EFFECT_DELAY, function(){ $(this).remove(); });
}

Spesa.operations.select = function(link, action)
{
    if (action == 'all' && $('#operation-list tbody tr.operation, #operation-list tbody tr.schedule').length > 0) {
		$("#operation-list tbody tr").addClass('selected').find(':checkbox').attr('checked', 'checked');
	} else if (action == 'none') {
		$("#operation-list tbody tr").removeClass('selected').find(':checkbox').removeAttr('checked');
	} else {
		$("#operation-list tbody tr").not('.' + action).removeClass('selected').find(':checkbox').removeAttr('checked');
		$("#operation-list tbody tr." + action).addClass('selected').find(':checkbox').attr('checked', 'checked');
	}
	$('#operation-list tbody tr.hidden')
		.removeClass('selected')
		.find(':checkbox')
		.removeAttr('checked');
	Spesa.operations.update_balance();
}

Spesa.utils.toCurrency = function(amount)
{
	amount = isNaN(amount)? 0 : amount;
	return amount.toFixed(2).toString().replace('.', ',');
}

Spesa.operations.update_balance = function()
{
	var amount, id, expenses = 0, incomes = 0, operation;

	$('#selected-only').each(function(){
		if (this.checked) {
			$('#operation-list').not('.hidden').find(':checkbox').each(function(){
				if (this.checked) {
					id = parseInt($(this).attr('id').replace(/(?:operation|schedule)-/, '')) - 1;
					operation = operations[id];
					expenses += operation.flow == 'in'? 0 : parseFloat(operation.attributes.amount);
					incomes += operation.flow == 'in'? parseFloat(operation.attributes.amount) : 0;
				}
			});
		} else {
			expenses = parseFloat(sums.expenses);
			incomes = parseFloat(sums.incomes);
		}
	});
	
	var month_balance = expenses + incomes;
	
	$('#incomes').html(Spesa.utils.toCurrency(incomes));
	$('#expenses').html(Spesa.utils.toCurrency(expenses));
	$('#month-balance').html(Spesa.utils.toCurrency(month_balance));
	$('#total').html(Spesa.utils.toCurrency(sums.residue + month_balance));
}

Spesa.operations.list = function()
{
	/* setting a.remove click event */
	$('a.remove').each(function(){
		$(this).click(function(){
			if (confirm('Tem certeza que deseja remover este lançamento?')) {
				var url = $(this).attr('href') + '?confirm=1';
				$(this).attr('href', url);
				return true;
			} else {
				return false;
			}
		});
	});

	$('p.page-nav a:first').after('<a href="javascript:;" class="month-picker">Escolher mês</a>');
	$('p.page-nav a.month-picker').monthPicker({start:2007, year:year, url:'/operations/%y/%m/list/', months:MONTHS_ABBR, close: 'Fechar', next: 'Próximo', previous: 'Anterior'});

	if ($('#operation-list tbody tr:first td:first').is('.no-operation')) {
		$('#action-form input, #action-form select').attr('disabled', 'disabled');
	}

	$('#operation-list').find(':checkbox').each(function(){
		$(this).click(function(){
			$(this).parents('tr').toggleClass('selected');
			Spesa.operations.update_balance();
		});
		this.checked? $(this).parents('tr').addClass('selected') : null;
	});

	$('#info').after('<div class="actions">' +
		'<p>'+
            '<strong>Selecione:</strong> '+
			'<a href="#" class="all">Todas</a>, ' +
			'<a href="#" class="none">Nenhuma</a>, ' +
			'<a href="#" class="income">Créditos</a>, ' +
			'<a href="#" class="expense">Débitos</a>, ' +
			'<a href="#" class="pending">Pendentes</a>, ' +
			'<a href="#" class="done">Pagas</a>, ' +
			'<a href="#" class="overdue">Atrasadas</a>, ' +
			'<a href="#" class="this_month">Este mês</a>' +
        '</p>' +
        '<p class="selected-only">'+
            '<input type="checkbox" id="selected-only" /> '+
            '<label for="selected-only">Calcular selecionados</label>'+
        '</p>' +
		'<p class="hide-paid">' +
            '<input type="checkbox" id="hide-paid" /> ' +
            '<label for="hide-paid">Ocultar lançamentos pagos</label>' +
        '</p>' +
        /*'<p class="hide-previous-month">' +
            '<input type="checkbox" id="hide-previous-month" /> ' +
            '<label for="hide-previous-month">Considerar somente este mês</label>' +
        '</p>' +*/
    '</div>');

	$('div.actions a').click(function(){
		Spesa.operations.select(this, this.className);
		return false;
	});

	$('#selected-only').click(function(){
		Spesa.operations.update_balance();
	});

	$('#hide-paid').click(function(){
		if (this.checked) {
			$('#operation-list tr.done')
				.not('.schedule')
				.removeClass('selected')
				.addClass('hidden')
				.find(':checkbox')
				.removeAttr('checked');
		} else {
			$('#operation-list tr.done').not('.schedule').removeClass('hidden');
		}

		cookie.set('hide_paid', (this.checked? 1 : 0), 86400*365, '/');
		Spesa.operations.update_balance();
	});

	if (cookie.get('hide_paid') == '1') {
		$('#operation-list tr.done').not('.schedule').addClass('hidden');
		$('#hide-paid').attr('checked', 'checked');
	}
}

Spesa.operations.edit = function()
{
	Spesa.schedules.init();
}

Spesa.operations['import'] = function()
{
	$('.import-now').add('.cancel').click(function(){
		$('#form').toggle();
		$('#description').toggle();
		return false;
	});
}

Spesa.schedules.tags = {};

Spesa.schedules.init = function()
{
	$('#tag_list').parents('p').after('<ul id="available-tags"></ul>');
	$('#tag_list').val(selected_tags.join(', '));

	var insensitive_sort = function(a,b){
		a = String(a).toUpperCase();
		b = String(b).toUpperCase();

		if (a > b) {
			return 1;
		}

		if (a < b) {
			return -1;
		}

		return 0;
	}

	var li = '', class_name;
	available_tags = available_tags.sort(insensitive_sort);

	for (var i=0, tag; tag = available_tags[i]; i++) {
		var exists = $.grep(selected_tags, function(selected_tag){
			return tag == selected_tag;
		});

		class_name = exists.length == 1? 'selected' : '';

		li += "<li><a href='#' rel='" + tag + "' class='" + class_name + "'>" + tag + "</a></li>";
	}

	$('#available-tags').html(li);
	$('#available-tags a').click(function(){
		var selected = $(this).is('.selected');
		var tag_list = $('#tag_list').val();
		var selected_tags = tag_list.split(/,( +)?/);
		selected_tags = selected_tags.sort();
		var selected_tag = $(this).text();
		var new_tag_list = [];

		if (!selected && selected_tags) {
			new_tag_list.push(selected_tag);
		}

		$(this).toggleClass('selected');

		for(var i = 0; i < selected_tags.length; i++) {
			var tag = selected_tags[i];

			if(tag.match(/^ +$/) || (selected && tag == selected_tag) || !tag){
				continue;
			}

			new_tag_list.push(tag);
		}

		new_tag_list = new_tag_list.sort(insensitive_sort);

		$('#tag_list').val(new_tag_list.join(', '));

		return false;
	});
}



Spesa.schedules.edit = function(){
	Spesa.schedules.add();
}

Spesa.schedules.add = function()
{
	var html = '<p><label for="schedule_mode">Vencimento</label><br/>' +
			'<select name="schedule[mode]" id="schedule_mode">' +
			(skip_once? '' : '<option value="once" class="schedule_mode_once">Apenas uma vez</option>') +
			'<option value="weekly" class="schedule_mode_weekly">Toda semana</option>' +
			'<option value="monthly" class="schedule_mode_monthly">Todo mês</option>'+
			'</select>' +
			(skip_once? '' : '<span class="item schedule_mode_once hide"> no dia </span>') +
			'<span class="item schedule_mode_weekly hide"> todo(a) </span>' +
			'<span class="item schedule_mode_monthly hide"> no dia </span>' +
			'</p>';

	$('fieldset.due').after(html);

	if (!skip_once) {
		$('#once-group').appendTo('span.schedule_mode_once');
	}
	$('#weekly-group').appendTo('span.schedule_mode_weekly');
	$('#monthly-group').appendTo('span.schedule_mode_monthly');

	$('#schedule_mode').change(function(){
		$('span.item').addClass('hide');
		$('span.schedule_mode_' + $(this).val()).removeClass('hide');

		if(this.value == 'once') {
			$('#repeat').hide();
		} else {
			$('#repeat').show();
		}
	});

	$('#schedule_repeats_forever').click(function(){
		if (this.checked) {
			$('#repeat select').attr('disabled', 'disabled');
		} else {
			$('#repeat select').removeAttr('disabled');
		}

	});

	var id = /*$('fieldset.due :checked').attr('id') || */(skip_once? 'schedule_mode_weekly' : 'schedule_mode_once');

	if (mode) {
		$('#schedule_mode option[@value=' + mode + ']').each(function(){ this.selected = true; });
	} else {
		$('#schedule_mode option.' + id).get(0).selected = true;
	}

	$('#schedule_mode').trigger('change');

	if($('#schedule_repeats_forever').is(':checked')) {
		$('#repeat select').attr('disabled', 'disabled');
	}

	$('fieldset.due').remove();

}

Spesa.account.index = function()
{
	/* setting a.remove click event */
	$('a.remove').each(function(){
		$(this).click(function(){
			if (confirm('Tem certeza que deseja remover este agendamento?')) {
				var url = $(this).attr('href') + '?confirm=1';

				$(this).attr('href', url);
				return true;
			} else {
				return false;
			}
		});
	});
}

Spesa.overview.index = function()
{
	$('#main').prepend(ads('full'));
}

jQuery.editable = function()
{
	$('.viewable .edit').click(function(){
		$(this).parents('.viewable').toggle();
		$('#edit-' + $(this).parents('.viewable').attr('id')).toggle();

		return false;
	});

	$('.editable .cancel').click(function(){
		$(this).parents('.editable').toggle();
		$('#' + $(this).parents('.editable').attr('id').replace(/^edit-/, '')).toggle();

		return false;
	});
}

jQuery.fn.replace = function(html)
{
	$(this).after(html);
	$(this).remove();
}
