var DefaultTimeline = null; // Will be filled in the $(document).ready call.

var MonthDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

var BrMonthNames = [
                    'Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio',
                    'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro',
                    'Novembro', 'Dezembro'
                    ];

var BrWeekDayNames = [
                      'Domingo', 'Segunda', 'Terça', 'Quarta', 'Quinta', 'Sexta', 'Sábado'
                      ];

var MaxObjectsInPerCol = 20;

/* Useful functions */

String.prototype.zfill = function(size) {
	var prefix = '';
	for (var i = 0; i < parseInt(size) - this.length; i++)
		prefix += '0';
	return prefix + this;
};

Date.prototype.toSString = function () {
	var year = this.getYear > 1900 ? this.getYear() : this.getYear() + 1900;
	return String(year) + '-' +
	String(this.getMonth()+1).zfill(2) + '-' +
	String(this.getDate()).zfill(2);
};

/* Returns true for leap years and false for non-leap years */
function isleap(year) {
	return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
}

/* Returns the last day of a month */
function lastMonthDay(year, month) {
	var lastDay = MonthDays[month];

	/* Handling february */
	if (month == 1 && isleap(year))
		lastDay++;
	return lastDay;
}

/* Compares the year, month and month day of two dates */
function dateCmp(date1, date2) {
	if (!date1 && date2)
		return false;
	if (date1 && !date2)
		return false;
	return (date1.getYear() == date2.getYear() &&
			date1.getMonth() == date2.getMonth() &&
			date1.getDate() == date2.getDate());
}

/* Timeline object. Controls month widget and the day list. */

function Timeline(date) {
	var broken = date.split('-');
	var year = broken[0], month = broken[1], day = broken[2];

	/* Holds timeline date. It is changed only when the month
	 * widget is changed. */
	this.startDate = new Date(year, parseInt(month)-1, day);

	/* This attribute holds the selected day in timeline. It *is*
	 * different from `startDate' because it'll only be set when
	 * user clicks in a day button. */
	this.selectedDate = null;
}

Timeline.prototype = {
		next: function() {
	var month = this.startDate.getMonth();
	this.startDate.setMonth(++month);
	this.updateMonth();
},

previous: function() {
	var month = this.startDate.getMonth();
	this.startDate.setMonth(--month);
	this.updateMonth();
},

updateMonth: function() {
	var mname = BrMonthNames[this.startDate.getMonth()];
	var year = this.getYear();
	$('#month-holder').html('<strong>' + mname + '</strong> - ' + year);
	this.loadDays();
},

loadDays: function() {
	var year = this.getYear();
	var month = String(this.startDate.getMonth()+1).zfill(2);
	var lastDay = lastMonthDay(this.getYear(), this.startDate.getMonth());

	/* Clearing everything up before loading the current month days. */
	$('ul.selecaoDia').html('');

	var monthStr = year + '-' + month;
	var oself = this;
	$.getJSON(BASE_URL + 'days/' + monthStr + '/', {}, function (data)
			{
		var tmpDate = new Date(year, month-1);

		/* Time to fill daylist widget again */
		for (var i = 0; i < data.length; i++) {
			tmpDate.setDate(data[i].day_num);

			var li = $('<li>')
			.appendTo($('ul.selecaoDia'));

			if (data[i].hascontent)
				li.addClass('comConteudo');

			if (dateCmp(tmpDate, oself.selectedDate)) {
				li.css({width: '60px', height: '47px', opacity: '4.0'});
				li.addClass('selecionado');
			}

			var strDate = tmpDate.toSString();
			var button = $('<button>')
			.attr('id', 'btn-' + strDate)
			.click(function () {
				var localDate = $(this).attr('id').replace('btn-', '');
				oself.selectDay(localDate);
			})
			.appendTo(li);

			$('<p>')
			.addClass('diaSemana')
			.html(BrWeekDayNames[tmpDate.getDay()])
			.appendTo(button);

			$('<p>')
			.addClass('dia')
			.html(data[i].day_num)
			.appendTo(button);
		}
			});
},

getYear: function () {
	var dyear = this.startDate.getYear();
	var year = dyear > 1900 ? dyear : dyear + 1900;
	return year;
},

selectDay: function (date) {
	/* Parsing date. */
	var broken = date.split('-');
	var year = broken[0], month = broken[1], day = broken[2];
	var tmpDate = new Date(year, parseInt(month)-1, day);

	/* We don't need to reload days */
	if (dateCmp(this.selectedDate, tmpDate))
		return;

	/* Setting our selected day holder to the choosen date. */
	this.selectedDate = tmpDate;

	/* It is better to clean the content of our timeline before loading
	 * new videos. */
	$('ul.listVideos').html('').hide();
	$('div.videoDestaque').html('').hide();
	$('.jcarousel-prev').hide();
	$('.jcarousel-next').hide();
	$('.containerTimeline').addClass('loading');

	/* Removing the `selected' class from all days and setting it
	 * in the clicked one. */
	$('ul.selecaoDia li').animate(
			{width: '22px', height: '34px'},
			400, 'linear', function () {
				$('ul.selecaoDia li').removeClass('selecionado');
			});

	$('#btn-' + date).parent().animate(
			{width: '60px', height: '47px', opacity: '4.0'},
			400, 'linear', function () {
				$('#btn-' + date).parent().addClass('selecionado');

				/* Time to do the hard work, load videos of that day. */
				var searchDate = year + '-' + String(month).zfill(2) + '-' +
				String(day).zfill(2);
				$.getJSON(BASE_URL + searchDate + '/', {}, function (data)
						{
					var ul = $('ul.listVideos');

					var dataColumns = [];
					for (var i = 0; i < data.length; i++) {
						var pos = parseInt(Math.floor(i/MaxObjectsInPerCol));
						var subli;
						if (dataColumns.length <= pos) {
							var li = $('<li>').appendTo(ul);
							var subul = $('<ul>').appendTo(li);
							dataColumns.push(subul);
						}
						subli = $('<li>');

						if (i == 2 || i == 6 || i == 22  || i == 26)
							subli.addClass('espaco');

						var link = $('<a>')
						.attr('href', BASE_URL + 'video/' + data[i].id + '/')
						.appendTo(subli);
						if ( data[i].special_banner == true) {
							$('<img>')
							.attr('src', BASE_URL + 'site_media/img/graph/faixa.png')
							.attr('class', 'faixa')
							.appendTo(link);
						}
						$('<img>')
						.attr('src', BASE_URL + 'thumb/' + data[i].id + '/')
						.appendTo(link);
						$('<h3>')
						.html(data[i].title)
						.appendTo(link);
						/* Bug de Layout
						$('<span>')
						.html("Comentarios " + data[i].comments)
						.appendTo(link);
						*/
						subli.appendTo(dataColumns[pos]);
						$('#mycarousel').jcarousel();
						$('ul.listVideos').fadeIn(1500);
					}
						});

				$.getJSON(BASE_URL + 'highlight/' + searchDate + '/', {}, function (data)
						{
					var theDiv = $('div.videoDestaque');

					/* It is possible to click in a day that does not have videos
					 * at all. */
					if (!data)
						return;

					var link = $('<a>')
					.attr('href', BASE_URL + 'video/' + data.id + '/')
					.appendTo($('div.videoDestaque'));
					/* Bug de Layout
					$('<span>')
					.html("Comentarios " + data.comments)
					.appendTo(link);
					*/
					if ( data.special_banner == true ) {
						$('<img>')
						.attr('src', BASE_URL + 'site_media/img/graph/faixaBig.png')
						.attr('class', 'faixa')
						.appendTo(link);
					}
					$('<img>')
					.attr('src', BASE_URL + 'bigthumb/' + data.id + '/')
					.appendTo(link);
					$('<h2>')
					.html(data.title)
					.appendTo(link);
					theDiv.fadeIn(1200);
					$('.jcarousel-prev').fadeIn(1000);
					$('.jcarousel-next').fadeIn(1000);
					$('.containerTimeline').removeClass('loading');
						});
			});
}
};

/* AjaxForm setup and validation stuff */

	function do_the_validation(data, formObj, options) {
		return validateForm(formObj);
	}

$(document).ready(function () {

	var optOOForm = {
		dataType: 'json',
		beforeSubmit: do_the_validation,
		success: function (response, responseText) {
		if (responseText == 'success' && response['status'] == 'ok') {
			showSuccessMessage('#outro-olhar');
		}

		if ( response['status'] == 'error' ) {
		//erro
		var message = response['message'];
		showErrorMessage('#outro-olhar', message);
		}
		//erro
		}

	};



	var optQuestionForm = {
	      dataType: 'json',
	      beforeSubmit:do_the_validation,
	      success: function (response, responseText) {
		if (responseText == 'success' && response['status'] == 'ok') {
			showSuccessMessage('#daily-question');
		}

		if ( response['status'] == 'error' ) {
		//erro
			var message = response['message'];
			showErrorMessage('#daily-question', message);
			}
		}
	};

	$('#outro-olhar').ajaxForm(optOOForm);
	$('#daily-question').ajaxForm(optQuestionForm);
	$('#faz_busca').click(function(){$('#form_busca').submit();})



	});
