var month_names = new Array("Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre");
var day_names = new Array("Domingo","Lunes","Martes","Miercoles","Jueves","Viernes","Sabado");

function mysqlTimeStampToDate(timestamp) {
	// function parses mysql datetime string and returns javascript Date object
	// input has to be in this format: 2007-06-05 15:26:02
	var regex=/^([0-9]{2,4})-([0-1][0-9])-([0-3][0-9]) (?:([0-2][0-9]):([0-5][0-9]):([0-5][0-9]))?$/;
	var parts=timestamp.replace(regex,"$1 $2 $3 $4 $5 $6").split(' ');
	return new Date(parts[0],parts[1]-1,parts[2],parts[3],parts[4],parts[5]);
}
 
function parse_date(string) {  
	var date = new Date();  
	var parts = String(string).split("-");  
	date.setFullYear(parts[0]);  
	date.setMonth(parts[1] - 1);  
	date.setDate(parts[2]);  
	return date;  
}

function parse_youtube_date(string) {  
	var date = new Date();  
	var parts = String(string).split("-");  
	date.setFullYear(parts[0]);  
	date.setMonth(parts[1] - 1);  
	date.setDate(parts[2]);  
	return date;  
}

function isoDateReviver(value) {
	if (typeof value === 'string') {
		var a = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)(?:([\+-])(\d{2})\:(\d{2}))?Z?$/.exec(value);
		if (a) {
			var utcMilliseconds = Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6]);
			return new Date(utcMilliseconds);
		}
	}
	return value;
}

function getCalendar(month,year,callback){
	
	$("#calendar").html("<img style='margin:0 auto;' alt='' src='img/ajax-loader-home.gif'></img>");
	var ajaxUrl="data/getCalendar.php?year="+year+"&month="+month;
	$.ajax({
		type: "POST",
		url: ajaxUrl,
		dataType: "html",
		error: function(data){
			$("#calendar").append("error occured, please refresh");
		},
		success: function(html) {
			$("#calendar").html(html);
			if(current++==0){getNextEvent();}
			setPopups();
			
			$("#currentMonth").html(month_names[date.getMonth()]+" "+date.getFullYear());
			
			$(".day-number.hasEvent").click(function(){
				var desc = $(".description",this).val();	
				var date = mysqlTimeStampToDate($(".date",this).val());
				var freq = $(".frequency",this).val();
				var thumb = $(".thumb",this).val();
				var title = $(".title",this).val();
				var id = $(".id",this).val();
				
				$("#agendaItemDay").html(day_names[date.getDay()]);
				$("#agendaItemNumber").html(date.getDate());
				$("#agendaItemMonth").html(month_names[date.getMonth()]);
				$("#agendaThumbnail").html("<img height='108px' width='163px' alt=''src='"+thumb+"'></img");
				$("#agendaFrequency").html(freq);
				$("#agendaDescription").html(desc);
				$("#agendaItemContent h3").html(title);
				$("#agendaLink").attr("href","agenda.php?id="+id);						
			});
			if(callback!=null){
				callback.call();
			}
		}
	});	
}

function setPopups(){
	$('.calendar-day').each(function () {
		// options
		var distance = 0;
		var time = 250;
		var hideDelay = 500;
		var hideDelayTimer = null;

		// tracker
		var beingShown = false;
		var shown = false;
	    
		var trigger = $('.day-number', this);
		var popup = $('.popup', this).css('opacity', 0);

		// set the mouseover and mouseout on both element
		$([trigger.get(0), popup.get(0)]).mouseover(function () {
			// stops the hide event if we move from the trigger to the popup element
			if (hideDelayTimer) clearTimeout(hideDelayTimer);
			// don't trigger the animation again if we're being shown, or already visible
			if (beingShown || shown) {
				return;
			} else {
				beingShown = true;
				// reset position of popup box
				popup.css({top: -70, left: -45, display: 'block' }).animate({
					top: '-=' + distance + 'px',
					opacity: 1
				}, time, 'swing', function() {
				// once the animation is complete, set the tracker variables
				beingShown = false;
				shown = true;
			});
		}
	}).mouseout(function () {
		// reset the timer if we get fired again - avoids double animations
		if (hideDelayTimer) clearTimeout(hideDelayTimer);
		// store the timer so that it can be cleared in the mouseover if required
		hideDelayTimer = setTimeout(function () {
			hideDelayTimer = null;
			popup.animate({top: '-=' + distance + 'px', opacity: 0}, time, 'swing', function () {
					// once the animate is complete, set the tracker variables
					shown = false;
					// hide the popup entirely after the effect (opacity alone doesn't do the job)
					popup.css('display', 'none');
				});
			}, hideDelay);
		});
	});
}

function getNextEvent(){
	
	// alert($("#nextEvent").html());
	// alert($("#nextEvent .date").val());
	// 2010-04-19 00:00:00
	
	var desc = $("#nextEvent .description").val();
	var date = mysqlTimeStampToDate($("#nextEvent .date").val());
	// error 
	var freq = $("#nextEvent .frequency").val();
	var thumb = $("#nextEvent .thumb").val();
	var title = $("#nextEvent .title").val();
	var id = $("#nextEvent .id").val();
	
	$("#agendaItemDay").html(day_names[date.getDay()]); // josef le había restado 1 [date.getDay()-1] ¿? 
	$("#agendaItemNumber").html(date.getDate());
	$("#agendaItemMonth").html(month_names[date.getMonth()]);
	$("#agendaThumbnail").html("<img height='108px' width='163px' alt=''src='"+thumb+"'></img");
	$("#agendaFrequency").html(freq);
	$("#agendaDescription").html(desc);
	$("#agendaItemContent h3").html(title);
	$("#agendaLink").attr("href","agenda.php?id="+id);
}

/**
 * Create String of Hours Minutes and Seconds
 * @param integer secs Number of seconds to convert
 * @return string
 */
function getTimeString(secs){
	var timeString ="";
	if(secs!=""){
		var timeObj = secondsToTime(secs);
		if(timeObj.m<10){timeObj.m = "0"+timeObj.m;}
		if(timeObj.s<10){timeObj.s = "0"+timeObj.s;}
		if(timeObj.h>0){timeString+= timeObj.h+":";}
		timeString += timeObj.m+":";
		timeString += timeObj.s;
	} else {
		timeString= "NaN";
	}
	return timeString;
}

/**
 * Convert number of seconds into time object
 *
 * @param integer secs Number of seconds to convert
 * @return object
 */

function secondsToTime(secs){
	
	var hours = Math.floor(secs/(60*60));
	var divisor_for_minutes = secs%(60*60);
	
	var minutes = Math.floor(divisor_for_minutes/60);
	var divisor_for_seconds = divisor_for_minutes%60;
	
	var seconds = Math.ceil(divisor_for_seconds);
	/* if(seconds<10){seconds ="0"+seconds;} */
	var obj = {
		"h": hours,
		"m": minutes,
		"s": seconds
	};
	return obj;
}

