/* Loads the Google data JavaScript client library */
google.load("gdata", "1");

currentCalendarAddress = 'argenteam.series.calendar@gmail.com';
today = new Date();
currentDate = today;

weekDays = new Array('Domingos','Lunes','Martes','Miércoles','Jueves','Viernes','Sábados');
weekDay = new Array('Domingo','Lunes','Martes','Miércoles','Jueves','Viernes','Sábado');

function init() {
  // init the Google data JS client library with an error handler
  google.gdata.client.init(handleGDError);
  $('calendarBox').setStyle('opacity',0);
  $('calendarBox').setStyle('display','block');
  var bTop = $('calendarTitle').getTop() + 50;
  var bLeft = $('calendarTitle').getLeft() - 150;
  bTop = (window.ie6) ? bTop/2 : bTop;
  bLeft = (window.ie6) ? bLeft/2 : bLeft;
  $('calendarBox').setStyle('top', bTop);
  $('calendarBox').setStyle('left', bLeft);  
  new Drag.Move($('calendarBox'), {handle: 'calControl'});
}

/**
 * Adds a leading zero to a single-digit number.  Used for displaying dates.
 */
function padNumber(num) {
  if (num <= 9) {
    return "0" + num;
  }
  return num;
}

function trim(str) {
	return str.replace(/^\s+/, '').replace(/\s+$/, '');
}

function addDays(date, days) {
	var rdate = new Date();
	rdate.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
	return rdate;
} 

function getShortDate(date) {
	return padNumber(date.getDate()) + "/" + (date.getMonth() + 1);
}

function loadTodaysCalendar() {
	currentDate = new Date();
	loadCurrentCalendar();
}

function loadCurrentCalendar() {
	loadCalendarByAddress(currentCalendarAddress,currentDate);
}

function openCalendar() {
	if($('calendarBox').getStyle('opacity') == 0) {
		loadTodaysCalendar();
	} else {
		closeCalendar();
	} 	
} 

function closeCalendar() {	
	$('calendarBox').set('tween', {duration: 1000, transition: Fx.Transitions.Quint.easeOut});
	$('calendarBox').tween('opacity',0);
	//$('calendarBox').tween('opacity', {duration: 1000, transition: Fx.Transitions.Quint.easeOut}).start($('calendarBox').getStyle('opacity'),0);
	
	if(window.ie6) {
		$('calendarEvents').setStyles({'opacity': 0 });
		$('calendarHeader').setStyles({'opacity': 0 });
		$('calendarFooter').setStyles({'opacity': 0 });
	}
	
}

function blockCalendar() {
	$('calendarEvents').setStyles({'opacity': 0.1 });
	$('calendarHeader').setStyles({'opacity': 0.1 });	
	$('calendarFooter').setStyles({'opacity': 0.1 });
	$('calendarBox').addClass('calendarBoxWait');
} 

function unBlockCalendar() {

	$('calendarEvents').setStyles({'opacity': 1 });
	$('calendarHeader').setStyles({'opacity': 1 });
	$('calendarFooter').setStyles({'opacity': 1 });
	$('calendarBox').removeClass('calendarBoxWait');	
	//$('calendarEvents').setStyles({'opacity': 1});	
} 


/**
 * Determines the full calendarUrl based upon the calendarAddress
 * argument and calls loadCalendar with the calendarUrl value.
 *
 * @param {string} calendarAddress is the email-style address for the calendar
 */ 
function loadCalendarByAddress(calendarAddress,date) {
	var calendarUrl = 'http://www.google.com/calendar/feeds/' +
                    calendarAddress + 
                    '/public/full';
 	loadCalendar(calendarUrl,date);
}

/**
 * Uses Google data JS client library to retrieve a calendar feed from the specified
 * URL.  The feed is controlled by several query parameters and a callback 
 * function is called to process the feed results.
 *
 * @param {string} calendarUrl is the URL for a public calendar feed
 */  
function loadCalendar(calendarUrl,date) {
	var service = new 
	google.gdata.calendar.CalendarService('argenteam-portal-series-calendar');
	var query = new google.gdata.calendar.CalendarEventQuery(calendarUrl);
	query.setOrderBy('starttime');
	query.setSortOrder('ascending');
	//query.setFutureEvents(true);
	query.setSingleEvents(true);	
	if(!date) date = currentDate; 
	var dateStr = date.getFullYear() +  "-" + padNumber(date.getMonth() + 1) + "-" +  padNumber(date.getDate());	
	query.setMinimumStartTime(google.gdata.DateTime.fromIso8601(dateStr + "T00:00:00.000-05:00"));
	query.setMaximumStartTime(google.gdata.DateTime.fromIso8601(dateStr + "T23:59:59.999-05:00"));
	service.queryDate = date;
	service.queryCalendarUrl = calendarUrl;
		
	service.getEventsFeed(query, listEvents, handleGDError);
}

/**
 * Callback function for the Google data JS client library to call when an error
 * occurs during the retrieval of the feed.  Details available depend partly
 * on the web browser, but this shows a few basic examples. In the case of
 * a privileged environment using ClientLogin authentication, there may also
 * be an e.type attribute in some cases.
 *
 * @param {Error} e is an instance of an Error 
 */
function handleGDError(e) {
	if($('jsSourceFinal'))	
  		$('jsSourceFinal').setStyle('display','none');
	if (e instanceof Error) {
		/* alert with the error line number, file and message */
		if(e.message.substr(0,19) != 'Unsupported browser')
			alert('Error at line ' + e.lineNumber +
			  ' in ' + e.fileName + '\n' +
			  'Message: ' + e.message);
		/* if available, output HTTP error code and status text */
		if (e.cause) {
		  var status = e.cause.status;
		  var statusText = e.cause.statusText;
		  alert('Root cause: HTTP error ' + status + ' with status text of: ' + 
		    statusText);
		}
	} else {		
			alert(e.toString());
	}
}

/**
 * Callback function for the Google data JS client library to call with a feed 
 * of events retrieved.
 *
 * Creates an unordered list of events in a human-readable form.  This list of
 * events is added into a div called 'events'.  The title for the calendar is
 * placed in a div called 'calendarTitle'
 *
 * @param {json} feedRoot is the root of the feed, containing all entries 
 */ 
function listEvents(feedRoot) {
	
	var entries = feedRoot.feed.getEntries();
	
	var eventDiv = $('calendarEvents');
	
	eventDiv.empty();
	/*
	if(!eventDiv.slider) {
		eventDiv.slider = new Fx.Slide('calendarEvents', {duration: 200});
	}
	*/
	
	var current = new Element('div', {'class': 'calCurrentWeek'});
	var coming = new Element('div', {'class': 'calComingWeek'});
	
	var calControls = new Element('div', {'id':'calControl'});
	
	dateBox = new Element('h3');
	dateBoxStrong = new Element('strong');
	dateBoxStrong.set('text',padNumber(currentDate.getDate()));
	dateBox.adopt(dateBoxStrong);
	dateBox.appendText("/" + (currentDate.getMonth() + 1));
	calControls.adopt(dateBox);
	
	var cExt = (window.ie6) ? "gif" : "png";

	var prevDayButton = new Element('img', {'src':'images/calendar-prev.'+cExt});
	prevDayButton.addEvent('click', function() {blockCalendar();currentDate = addDays(currentDate,-1);loadCurrentCalendar()});
	if(currentDate < addDays(today,-2)) {		
		prevDayButton.setStyle('visibility','hidden');
	}
	calControls.adopt(prevDayButton);
	
	var todayButton = new Element('img', {'src':'images/calendar-home.'+cExt});
	todayButton.addEvent('click', function() {blockCalendar();loadTodaysCalendar()});
	calControls.adopt(todayButton);
	
	var nextDayButton = new Element('img', {'src':'images/calendar-next.'+cExt});
	nextDayButton.addEvent('click', function() {blockCalendar();currentDate = addDays(currentDate,1);loadCurrentCalendar()});
	if(currentDate > addDays(today,7)) {		
		nextDayButton.setStyle('visibility','hidden');
	}
	calControls.adopt(nextDayButton);
	
	var closeButton = new Element('img', {'src':'images/calendar-close.'+cExt, 'class':'calClose'});
	closeButton.addEvent('click', function() {closeCalendar()});
	calControls.adopt(closeButton);
	
	var dayBox = new Element('span', {'class':'calDay'});
	dayBox.set('text',weekDay[currentDate.getDay()]);
	calControls.adopt(dayBox);
	if(window.opera) dayBox.setStyle('margin-top','0px');
	if(window.ie7) dayBox.setStyle('margin','-8px 0 -4px 17px');
		
	eventDiv.adopt(calControls);
	
	comingTitle = new Element('h3');
	comingTitle.set('text','Próximamente los ' + weekDays[currentDate.getDay()]);
	coming.adopt(comingTitle);
		
	var len = entries.length;
	for (var i = 0; i < len; i++) {
		var entry = entries[i];
		entryDOM = createCalEntry(entry);
		if(entryDOM.hasClass('calEntryComing')) {
			coming.adopt(entryDOM);
		} else {
			current.adopt(entryDOM);
		}
	}
	
	if(coming.getChildren().length == 1) {
		comingNoItems = new Element('span', {'class':'calNoEvents'});
		comingNoItems.set('text','No se han encontrado eventos');
		coming.adopt(comingNoItems);
	}
	
	if(current.getChildren().length == 0) {
		currentNoItems = new Element('span', {'class':'calNoEvents'});
		currentNoItems.set('text','No se han encontrado eventos');
		current.adopt(currentNoItems);
	}
	if(window.ie7) current.setStyle('margin-top','-4px');
	
	
	eventDiv.adopt(current);
	eventDiv.adopt(coming);	
	
	unBlockCalendar();
	
	//$('calendarBox').tween('opacity', {duration: 1000, transition: Fx.Transitions.Quint.easeOut}).start($('calendarBox').getStyle('opacity'),1);
	$('calendarBox').set('tween', {duration: 1000, transition: Fx.Transitions.Quint.easeOut});
	$('calendarBox').tween('opacity',1);
	//eventDiv.slider.slideIn('horizontal');
}

function parseDescriptionData(desc) {
	parts = desc.split('\* ');
	descArray = new Array();
	for(i=0; i<parts.length; i++) {
		line = parts[i];
		keyPos = line.indexOf(':');
		if(keyPos >= 0) {			 
			descArray[trim(line.substr(0,keyPos))] = trim(line.substr(keyPos+1));
		} else {
			descArray[trim(line)] = '1';
		}				
	}
	return descArray;
}

function createCalEntry(entry) {
	
	entryData = parseDescriptionData(entry.getContent().getText());
	
	entryData['title'] = entry.getTitle().getText();
	
    var startDateTime = null;
    var startJSDate = null;
    var times = entry.getTimes();
    if (times.length > 0) {
      startDateTime = times[0].getStartTime();
      startJSDate = startDateTime.getDate();
    }
    
	entryData['shortDate'] = padNumber(startJSDate.getDate()) + "/" + (startJSDate.getMonth() + 1);
	entryData['date'] =  padNumber(startJSDate.getDate()) + "/" + padNumber(startJSDate.getMonth() + 1) + "/" + startJSDate.getFullYear();
	entryData['time'] = (!startDateTime.isDateOnly()) ? startJSDate.getHours() + ":" + padNumber(startJSDate.getMinutes()) : ""; 
	
	var entryDOM = new Element('div', {'class': 'calEntry'});
	    
	entryLink = new Element('a', {'href':entryData['Pack'], 'class':'calLink', 'target':'_blank'});
	entryLink.set('text',entryData['title']);
	entryDOM.adopt(entryLink);
	
	
	
	if(entryData['Emision']) {
		entryRelease = new Element('span', {'class' : 'calRelease'});
		entryRelease.set('text','Sale: ' + entryData['Emision']);
		entryDOM.adopt(entryRelease);
		entryDOM.addClass('calEntryComing');
	}	
	
	var calEntryDesc = new Element('div', {'class': 'calEntryDesc'});
	
	entryTime = new Element('span', {'class' : 'calTime'});
	entryTime.set('text',entryData['time']);
	calEntryDesc.adopt(entryTime);
	
	if(entryData['Temporada']) {
		entrySeason = new Element('span', {'class' : 'calSeason'});
		entrySeason.set('text','Temp. ' + entryData['Temporada']);
		calEntryDesc.adopt(entrySeason);
	}
	
	if(entryData['Episodio']) {
		entryEpisode = new Element('span', {'class' : 'calEpisode'});
		entryEpisode.set('text','Ep. ' + entryData['Episodio']);
		calEntryDesc.adopt(entryEpisode);
	}
	
	if(entryData['aFF']) {
		entryAFF = new Element('a', { 'href' : 'http://www.argenteam.net/soft/aff' , 'title' : 'aFF'});
		entryAFF.adopt(new Element('img', {'src' : 'images/calendar-aff.png'}));		
	} else {
		entryAFF = new Element('a', { 'href' : 'http://www.argenteam.net/soft/aff' , 'title' : 'Sin aFF'});
		entryAFF.adopt(new Element('img', {'src' : 'images/calendar-aff-disabled.png'}));
	}
	calEntryDesc.adopt(entryAFF);
	
	if(entryData['RSS Torrent ID']) {
		entryTorrent = new Element('a', 
					{ 	'href' : 'http://foro.argenteam.net/viewtopic.php?t=88681' , 
						'title' : 'RSS Torrent ID: '+entryData['RSS Torrent ID']
					});
		entryTorrent.adopt(new Element('img', {'src' : 'images/calendar-torrent.png'}));		
	} else {
		entryTorrent = new Element('a', 
					{	'href' : 'http://foro.argenteam.net/viewtopic.php?t=88681' , 
						'title' : 'Sin RSS Torrent'
					});
		entryTorrent.adopt(new Element('img', {'src' : 'images/calendar-torrent-disabled.png'}));
	}
	calEntryDesc.adopt(entryTorrent);
	
	entryDOM.adopt(calEntryDesc);
	
	return entryDOM;
} 

google.setOnLoadCallback(init);

