/* Loads the Google data JavaScript client library */
google.load("gdata", "2.x");

var nottolist = new Array();
nottolist[0]='Id-e-Milad';
nottolist[1]='Good Friday';
nottolist[2]='Ramjaan Id';
nottolist[3]='Bakrid';
nottolist[4]='Moharram';
nottolist[5]='Christmas';

var monthname=new Array();
monthname[0]='Jan';
monthname[1]='Feb';
monthname[2]='Mar';
monthname[3]='Apr';
monthname[4]='May';
monthname[5]='Jun';
monthname[6]='Jul';
monthname[7]='Aug';
monthname[8]='Sep';
monthname[9]='Oct';
monthname[10]='Nov';
monthname[11]='Dec';

var weekday=new Array(7);
weekday[0]="Sunday";
weekday[1]="Monday";
weekday[2]="Tuesday";
weekday[3]="Wednesday";
weekday[4]="Thursday";
weekday[5]="Friday";
weekday[6]="Saturday";

var sweekday=new Array(7);
sweekday[0]="Sun";
sweekday[1]="Mon";
sweekday[2]="Tue";
sweekday[3]="Wed";
sweekday[4]="Thu";
sweekday[5]="Fri";
sweekday[6]="Sat";

var eventdivid='';
var titledivid = '';
MONTH_OFFSET = 1;

var ekadashi  = false;
var festivals = false;
var poornima  = false;
var japdhyan  = false;
var ashramspl = false;

var SCHEDULE_CALENDAR = "d05mh9g7mgj4v0bcmftsk05c0g@group.calendar.google.com";
var ASHRAMSPL_CALENDAR = "l3hve6ttp2f2rb75hq8s9b3dro@group.calendar.google.com";
var EKADASHI_CALENDAR  = "to8t9ap66rnp17elrhhrp1t3j0@group.calendar.google.com";
var FESTIVALS_CALENDAR = "8460noi6fa9hprpppeavmmbptc@group.calendar.google.com";
var POORNIMA_CALENDAR  = "k48sn37ago87uetlju1fcajpos@group.calendar.google.com";
var JAPDHYAN_CALENDAR  = "gulpeci4o7np0tltqe1vh7etao@group.calendar.google.com";

var ashramspl_events = new Array();
var ekadashi_events  = new Array();
var festivals_events = new Array();
var japdhyan_events  = new Array();
var poornima_events  = new Array();

function init() {
  // init the Google data JS client library with an error handler
  google.gdata.client.init(handleGDError);
  // load the code.google.com developer calendar
  
}
/**
 * Loads the Google Developers Event Calendar
 */
function loadScheduleCalendar() {
	loadCalendarByAddress(SCHEDULE_CALENDAR);
	
}
function loadPoornimaCalendar() {
	loadCalendarByAddress(POORNIMA_CALENDAR);
}

function loadAllTithisCalendars(){
	loadCalendarByAddressTithis(ASHRAMSPL_CALENDAR);
	loadCalendarByAddressTithis(JAPDHYAN_CALENDAR);
	loadCalendarByAddressTithis(EKADASHI_CALENDAR);
	loadCalendarByAddressTithis(FESTIVALS_CALENDAR);
	loadCalendarByAddressTithis(POORNIMA_CALENDAR);
	
}

/**
 * Adds a leading zero to a single-digit number.  Used for displaying dates.
 */
function padNumber(num) {
  if (num <= 9) {
    return "0" + num;
  }
  return num;
}

/**
 * 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) {
  var calendarUrl = 'http://www.google.com/calendar/feeds/' +
                    calendarAddress + 
                    '/public/full';
  loadCalendar(calendarUrl);
}

function loadCalendarByAddressTithis(calendarAddress) {
  var calendarUrl = 'http://www.google.com/calendar/feeds/' +
                    calendarAddress + 
                    '/public/full';
  var service = new 
  google.gdata.calendar.CalendarService(calendarAddress); // just to differentiate different services.
  var query = new google.gdata.calendar.CalendarEventQuery(calendarUrl);
  query.setOrderBy('starttime');
  query.setSortOrder('ascending');
  query.setFutureEvents(false);
  query.setSingleEvents(true);
  var todaysDate = new Date();
  query.setMinimumStartTime(todaysDate.format('Y-m-d'));
  todaysDate.setMonth(todaysDate.getMonth()+ MONTH_OFFSET);
  query.setMaximumStartTime(todaysDate.format('Y-m-d'));
  query.setMaxResults(30);

	if ( calendarAddress == ASHRAMSPL_CALENDAR )	
		service.getEventsFeed(query, listAshramSplCalendarEvents, handleGDError);
	if ( calendarAddress == EKADASHI_CALENDAR )	
		service.getEventsFeed(query, listEkadashiCalendarEvents, handleGDError);
	if ( calendarAddress == FESTIVALS_CALENDAR )	
		service.getEventsFeed(query, listFestivalCalendarEvents, handleGDError);
	if ( calendarAddress == JAPDHYAN_CALENDAR )	
		service.getEventsFeed(query, listJapDhyanCalendarEvents, handleGDError);	
	if ( calendarAddress == POORNIMA_CALENDAR )	
		service.getEventsFeed(query, listPoornimaCalendarEvents, handleGDError);
	
}

function listAshramSplCalendarEvents(feedRoot){
  var entries = feedRoot.feed.getEntries(); 
  ashramspl = true;
  ashramspl_events = entries;
  listTithisEvents();
}


function listEkadashiCalendarEvents(feedRoot){
  var entries = feedRoot.feed.getEntries(); 
  ekadashi = true;
  ekadashi_events = entries;
  listTithisEvents();
}

function listFestivalCalendarEvents(feedRoot){
  var entries = feedRoot.feed.getEntries(); 
  festivals = true;
  festivals_events = entries;
  listTithisEvents();
}

function listJapDhyanCalendarEvents(feedRoot){
  var entries = feedRoot.feed.getEntries(); 
  japdhyan = true;
  japdhyan_events = entries;
  listTithisEvents();
}

function listPoornimaCalendarEvents(feedRoot){
  var entries = feedRoot.feed.getEntries(); 
  poornima = true;
  poornima_events = entries;
  listTithisEvents();
}

function listTithisEvents(){
	
	if( ekadashi  && festivals && poornima  &&  japdhyan  && ashramspl ){
		entries = new Array();
		entries = entries.concat(ashramspl_events, ekadashi_events, festivals_events , japdhyan_events, poornima_events );
		entries = entries.sort(sortevents)
		titledivid = 'tithiTitle';
		eventdivid = 'tithiEvents';
		listEvents(entries, "Upcoming Tithis", titledivid, eventdivid );
	}
}

function sortevents(a,b){

	var times_a = a.getTimes();
    if (times_a.length > 0) {
      startDateTime_a = times_a[0].getStartTime();
      endDateTime_a = times_a[0].getEndTime();
      startJSDate_a = startDateTime_a.getDate();
      endJSDate_a = endDateTime_a.getDate();
    }
	
	var times_b = b.getTimes();
    if (times_b.length > 0) {
      startDateTime_b = times_b[0].getStartTime();
      endDateTime_b = times_b[0].getEndTime();
      startJSDate_b = startDateTime_b.getDate();
      endJSDate_b = startDateTime_b.getDate();
    }
	
	return startJSDate_a - startJSDate_b;
	
}

/**
 * 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) {
  var service = new 
      google.gdata.calendar.CalendarService('gdata-js-client-samples-simple');
  var query = new google.gdata.calendar.CalendarEventQuery(calendarUrl);
  query.setOrderBy('starttime');
  query.setSortOrder('ascending');
  query.setFutureEvents(true);
  query.setSingleEvents(true);
  query.setMaxResults(30);

  service.getEventsFeed(query, listSingleCalendarEvents, 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) {
  document.getElementById('jsSourceFinal').setAttribute('style', 
      'display:none');
  if (e instanceof Error) {
    /* alert with the error line number, file and message */
    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 listSingleCalendarEvents(feedRoot) {
  var entries = feedRoot.feed.getEntries(); 
  titledivid = 'scheduleTitle';
  eventdivid = 'scheduleEvents';
  listEvents(entries, feedRoot.feed.title.$t , titledivid, eventdivid);
}

function listEvents(entries, titleHead, titledivid, eventdivid ){
	
var eventDiv = document.getElementById(eventdivid);
/*
  if (eventDiv.childNodes.length > 0) {
    eventDiv.removeChild(eventDiv.childNodes[0]);
  }	  */
  
  /* create a new unordered list */
  $("#"+eventdivid).html('');
  var len = entries.length;

  /* set the calendarTitle div with the name of the calendar */
  if(len>0){
  document.getElementById(titledivid).innerHTML = 
    "<b>" + titleHead + ":</b>";
  }
  else{
	$("#"+titledivid, $("#"+titledivid).parent()).remove();
  }
  /* loop through each event in the feed */
  for (var i = 0; i < len; i++) {
    var entry = entries[i];
    var title = entry.getTitle().getText();
	
	
	// Skip few festivals
	var skip = false;
	for(var s = 0 ; s < nottolist.length ; s++){
		if(title == nottolist[s]){
			skip = true;
			break;
		}
	}
	if(skip){
		continue;
	}
	
	
	var content = entry.getContent().getText();
	content = content.replace(/\n/g,'<br>');
    var startDateTime = null;
    var endDateTime = null;
    var startJSDate = null;
    var endJSDate = null;
    var times = entry.getTimes();
    if (times.length > 0) {
      startDateTime = times[0].getStartTime();
      endDateTime = times[0].getEndTime();
      startJSDate = startDateTime.getDate();
      endJSDate = endDateTime.getDate();
    }
    var entryLinkHref = null;
    if (entry.getHtmlLink() != null) {
      entryLinkHref = entry.getHtmlLink().getHref();
    }
    //var dateString = (startJSDate.getMonth() + 1) + "/" + startJSDate.getDate() + " to " + (endJSDate.getMonth() + 1) + "/" + ( endJSDate.getDate() -1) ; // end date -1 is made bcoz event will end on nextday 1st sec.
	sdate=startJSDate.getDate();	
	smonth=startJSDate.getMonth();
	sday=startJSDate.getDay();
	var tmp=new Date();
	tmp.setTime(endJSDate.getTime()-1);// end date -1 is made bcoz event will end on nextday 1st sec.
	endJSDate=tmp;
	edate=endJSDate.getDate();
	emonth=endJSDate.getMonth();
	eday=endJSDate.getDay();
	var dateString ="";
	var whenString ="";
	
	dateString = sdate + daySuffix(sdate);
	whenString = sdate + daySuffix(sdate) + monthname[smonth] + "("+sweekday[sday] + ")";	
	if( (smonth!=emonth) || ( (sdate==edate) && (smonth==emonth) ) ) {
		dateString+= monthname[smonth] ;		
		//whenString+= monthname[smonth] + "("+weekday[sday] + ")";		
	}
	if( !( (sdate==edate) && (smonth==emonth) ) ){
		dateString+=" - " + edate + daySuffix(edate)+ monthname[emonth]
		whenString+=" - " + edate + daySuffix(edate)+ monthname[emonth] + "("+sweekday[eday] + ")";		
	}

   // var dateString = endDateTime.getDate() ; // end date -1 is made bcoz event will end on nextday 1st sec.
    if (!startDateTime.isDateOnly()) {
      dateString += " " + startJSDate.getHours() + ":" + 
          padNumber(startJSDate.getMinutes());
    }
    var h4 = document.createElement('h4');
	
    /* if we have a link to the event, create an 'a' element */
    if (entryLinkHref != null) {
      entryLink = document.createElement('a');
      entryLink.setAttribute('href', "javascript:void(0)");
	  //entryLink.setAttribute('title', content);	 
	  $(entryLink).css('color', '#C0472F');	 
	  $(entryLink).css('text-decoration', 'underline');	
	  
	  obj={
		title:title,
		href:entryLinkHref,
		when:whenString,
		description:content
	  };
	  
	 // attach listener
		$(entryLink).bind('click', obj, function(event) {
		  showpopup(event);
		});
		
/* 		$(entryLink).bind('mouseout', obj, function(event) {
		  $("#popup-details").hide();
		});
 */		
	  //entryLink.setAttribute('onmouseover', 'showpopup('+obj+')');
      entryLink.appendChild(document.createTextNode(title));
	  var titlespan = document.createElement('span');
	  
	  // $('<span> '+dateString+': </span>').css('color','rgb(0, 153, 0)')
									  // .appendTo($(h4));
	
	$('<span>'+dateString+': </span>').css('color','rgb(0, 153, 0)')
									  .appendTo($(h4));
									  
	  $(entryLink).appendTo($('<span></span>').css('color','rgb(192, 71, 47)')
											  .appendTo($(h4)))
	  
//	 $('<span> ('+dateString+')</span>').css('color','rgb(0, 153, 0)')
									  .appendTo($(h4));
	   
    } else {
      h4.appendChild(document.createTextNode(title + ' - ' + dateString));
    }	    

	//$("#popup-details").show();
    /* append the list item onto the unordered list */
    eventDiv.appendChild(h4);
  }
}

function showpopup(event){

	obj = event.data;
	$("#popup-details").css('top', event.pageY)
	$("#popup-details").css('left', event.pageX)
	
	$(".title", $("#popup-details")).html(obj.title);
	$(".event-when", $("#popup-details")).html(obj.when);
	$("#moredetails", $("#popup-details")).attr('href',obj.href);
	$(".event-description", $("#popup-details")).html(obj.description);
	
	// Joomla fix
	$("#cal-title", $("#popup-details")).html(obj.title);
	$("#cal-event-when", $("#popup-details")).html(obj.when);	
	$("#cal-event-description", $("#popup-details")).html(obj.description);
	
	$("#popup-details").show();
}

function daySuffix(d) {
    d = String(d);
    if (d.substr(-(Math.min(d.length, 2))) > 3 && d.substr(-(Math.min(d.length, 2))) < 21 )
		return "th" ;
	
	return	["th", "st", "nd", "rd", "th"][Math.min(Number(d)%10, 4)];
}

google.setOnLoadCallback(init);

/*
*
*/

 
// Simulates PHP's date function
Date.prototype.format = function(format) {
	var returnStr = '';
	var replace = Date.replaceChars;
	for (var i = 0; i < format.length; i++) {
		var curChar = format.charAt(i);
		if (i - 1 >= 0 && format.charAt(i - 1) == "\\") { 
			returnStr += curChar;
		}
		else if (replace[curChar]) {
			returnStr += replace[curChar].call(this);
		} else if (curChar != "\\"){
			returnStr += curChar;
		}
	}
	return returnStr;
};
 
Date.replaceChars = {
	shortMonths: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
	longMonths: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
	shortDays: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
	longDays: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
	
	// Day
	d: function() { return (this.getDate() < 10 ? '0' : '') + this.getDate(); },
	D: function() { return Date.replaceChars.shortDays[this.getDay()]; },
	j: function() { return this.getDate(); },
	l: function() { return Date.replaceChars.longDays[this.getDay()]; },
	N: function() { return this.getDay() + 1; },
	S: function() { return (this.getDate() % 10 == 1 && this.getDate() != 11 ? 'st' : (this.getDate() % 10 == 2 && this.getDate() != 12 ? 'nd' : (this.getDate() % 10 == 3 && this.getDate() != 13 ? 'rd' : 'th'))); },
	w: function() { return this.getDay(); },
	z: function() { var d = new Date(this.getFullYear(),0,1); return Math.ceil((this - d) / 86400000); }, // Fixed now
	// Week
	W: function() { var d = new Date(this.getFullYear(), 0, 1); return Math.ceil((((this - d) / 86400000) + d.getDay() + 1) / 7); }, // Fixed now
	// Month
	F: function() { return Date.replaceChars.longMonths[this.getMonth()]; },
	m: function() { return (this.getMonth() < 9 ? '0' : '') + (this.getMonth() + 1); },
	M: function() { return Date.replaceChars.shortMonths[this.getMonth()]; },
	n: function() { return this.getMonth() + 1; },
	t: function() { var d = new Date(); return new Date(d.getFullYear(), d.getMonth(), 0).getDate() }, // Fixed now, gets #days of date
	// Year
	L: function() { var year = this.getFullYear(); return (year % 400 == 0 || (year % 100 != 0 && year % 4 == 0)); },	// Fixed now
	o: function() { var d  = new Date(this.valueOf());  d.setDate(d.getDate() - ((this.getDay() + 6) % 7) + 3); return d.getFullYear();}, //Fixed now
	Y: function() { return this.getFullYear(); },
	y: function() { return ('' + this.getFullYear()).substr(2); },
	// Time
	a: function() { return this.getHours() < 12 ? 'am' : 'pm'; },
	A: function() { return this.getHours() < 12 ? 'AM' : 'PM'; },
	B: function() { return Math.floor((((this.getUTCHours() + 1) % 24) + this.getUTCMinutes() / 60 + this.getUTCSeconds() / 3600) * 1000 / 24); }, // Fixed now
	g: function() { return this.getHours() % 12 || 12; },
	G: function() { return this.getHours(); },
	h: function() { return ((this.getHours() % 12 || 12) < 10 ? '0' : '') + (this.getHours() % 12 || 12); },
	H: function() { return (this.getHours() < 10 ? '0' : '') + this.getHours(); },
	i: function() { return (this.getMinutes() < 10 ? '0' : '') + this.getMinutes(); },
	s: function() { return (this.getSeconds() < 10 ? '0' : '') + this.getSeconds(); },
	u: function() { var m = this.getMilliseconds(); return (m < 10 ? '00' : (m < 100 ?
'0' : '')) + m; },
	// Timezone
	e: function() { return "Not Yet Supported"; },
	I: function() { return "Not Yet Supported"; },
	O: function() { return (-this.getTimezoneOffset() < 0 ? '-' : '+') + (Math.abs(this.getTimezoneOffset() / 60) < 10 ? '0' : '') + (Math.abs(this.getTimezoneOffset() / 60)) + '00'; },
	P: function() { return (-this.getTimezoneOffset() < 0 ? '-' : '+') + (Math.abs(this.getTimezoneOffset() / 60) < 10 ? '0' : '') + (Math.abs(this.getTimezoneOffset() / 60)) + ':00'; }, // Fixed now
	T: function() { var m = this.getMonth(); this.setMonth(0); var result = this.toTimeString().replace(/^.+ \(?([^\)]+)\)?$/, '$1'); this.setMonth(m); return result;},
	Z: function() { return -this.getTimezoneOffset() * 60; },
	// Full Date/Time
	c: function() { return this.format("Y-m-d\\TH:i:sP"); }, // Fixed now
	r: function() { return this.toString(); },
	U: function() { return this.getTime() / 1000; }
};
