/**
 * ProxyCal: Track your college attendance
 * Licensed under the GPL license (http://www.gnu.org/licenses/gpl.html)
 * Copyright (C) Ankit Ahuja
 *
 **/

/*globals*/

var token;
var num;
var cutoff = 75;
var calendars = [];
var calendarService;
var calendarId;
var events=[];
var current_day = Date.today().setTimezoneOffset(+530);
var timezone_offset ="+0:00";
var events_to_add = [];
var events_to_add_no = 0;

var ProxyCal = {
	
	//Login into google account (using AuthSub)
	logIn: function(){
		var scope = "http://www.google.com/calendar/feeds";
		ProxyCal.generateLoader("Logging in...");
		//Redirecting for Google Authentication to obtain the session cookie and consequently the subsession cookie
		var token = google.accounts.user.login(scope);
	},
	
	//To logout the user
	logOut: function(){
		ProxyCal.generateLoader("Logging Out...");
		google.accounts.user.logout();
		document.getElementById("cal").innerHTML="You successfully logged out!<br/><a href='proxycal.php'>Click Here<\/a> to refresh page";
	},
	
	//First function to execute after the body of the page completes loading
	checkLogIn: function(){
		ProxyCal.generateLoader("Authenticating...");
		scope = "http://www.google.com/calendar/feeds";
		var token = google.accounts.user.checkLogin(scope);
		return token;
	},
	
	_run: function(){
		calendarService = new google.gdata.calendar.CalendarService('proxycal');
		ProxyCal.generateLoader("Loading Calendar...");
		var token = ProxyCal.checkLogIn();
		if(token!="")
			ProxyCal.getFeed();
		else
		{
			var cal = document.getElementById("cal");
			cal.innerHTML = "Trying to log in. If nothing happens, you need to login into your Google Account. Do so by clicking <a href='#' onclick='ProxyCal.logIn()'>here<a>";
		}
	},
	getCalendarId: function(){
		var entries = calendars;
		for(var i=0;i<entries.length;i++)
		{
			var calendarEntry= entries[i];
			var calendarTitle= calendarEntry.getTitle().getText();
			if(calendarTitle == "ProxyCal")
			{
				var id = calendarEntry.getSelfLink().href.slice(63);
				return id;
			}
		}
	},
	//Get the User Settings page
	openSettings: function(){
		location.href = "settings?calid="+calendarId;
	},
	
	//Get the existing calendars for the authenticated Google Account
	generateLoader:function(subtext){
		var cal = document.getElementById("cal");
		cal.innerHTML = "<span class='loadingtext'>"+subtext+"</span>";
		cal.innerHTML += "<br/><img src='images/ajax-loader.gif' class='loader'/>";
	},
	
	//Create calendar ProxyCal if it doesn't exist already
	createCalendar: function(){
		var cal = document.getElementById("cal");
		var feedUri = 'http://www.google.com/calendar/feeds/default/owncalendars/full';

		// Create an instance of CalendarEntry, representing the new calendar
		var entry = new google.gdata.calendar.CalendarEntry();

		// Set the calendar title
		entry.setTitle(google.gdata.Text.create('ProxyCal'));

		// Set the calendar summary
		var summary = new google.gdata.Text();
		summary.setText('Managing your college attendance better.');
		entry.setSummary(summary);

		// Set the calendar timezone
		var timeZone = new google.gdata.calendar.TimeZoneProperty();
		timeZone.setValue('Asia/Calcutta');
		entry.setTimeZone(timeZone);

		// Set the calendar location
		var where = new google.gdata.Where();
		where.setLabel('New Delhi, India');
		where.setValueString('New Delhi, India');
		entry.addLocation(where);

		// Set the calendar to be visible in the Google Calendar UI
		var hidden = new google.gdata.calendar.HiddenProperty();
		hidden.setValue(false);
		entry.setHidden(hidden);

		// Set the color that represent this calendar in the Google Calendar UI
		var color = new google.gdata.calendar.ColorProperty();
		color.setValue('#66AA00');
		entry.setColor(color);

		// The callback method that will be called after a successful
		// insertion from insertEntry()
		var callback = function(result) {
		  cal.innerHTML = "ProxyCal Calendar successfully created!";
		  ProxyCal.getFeed();
		}

		// Error handler will be invoked if there is an error from insertEntry()
		var handleError = function(error) {
		  alert(error);
		}

		// Submit the request using the calendar service object
		calendarService.insertEntry(feedUri, entry, callback,
		    handleError, google.gdata.calendar.CalendarEntry);
	},
	
	getNextMonth:function(){
		var today = Date.today().setTimezoneOffset(+530);
		current_day.addMonths(1);
		if((today.getMonth() < current_day.getMonth() && parseInt(today.toString('yyyy')) == parseInt(current_day.toString('yyyy'))) || parseInt(today.toString('yyyy')) < parseInt(current_day.toString('yyyy')))
		{
			events.length=0;
			ProxyCal.displayCalendar();
		}
		else
		{
			ProxyCal.getEvents();
		}
	},

	getPreviousMonth:function(){
		var today = Date.today().setTimezoneOffset(+530);
		current_day.addMonths(-1);
		if(today.getMonth() < current_day.getMonth() && parseInt(today.toString('yyyy')) == parseInt(current_day.toString('yyyy')) || parseInt(today.toString('yyyy')) < parseInt(current_day.toString('yyyy')))
		{
			events.length=0;
			ProxyCal.displayCalendar();
		}
		else
			ProxyCal.getEvents();
	},

	//To get the attendance percentage for the current month on display
	getPercentage: function(attended,off,future,total)
	{
		total = total - off - future;
		percentage = ((attended/total)*100).toFixed(2);
		return percentage;
	},
	
	//To calculate no. of leaves that the user can take in the current month
	calcAvailableLeaves: function(attended,off,future,total,leaves)
	{
		var no_of_holidays = 0;
		temp_day = current_day;
		temp_day.moveToFirstDayOfMonth();
		for(i = 1;i <= total; i++)
		{
			if(temp_day.getDayName()=="Sunday" || temp_day.getDayName()=="Saturday")
			{
				no_of_holidays++;
			}
			temp_day.set({day:i});
		}
		cal  = document.getElementById("cal");
		total_days_to_go = (cutoff/100)*(total - no_of_holidays); //cutoff percent of the no. of working days
		leaves_allowed = total - total_days_to_go - no_of_holidays;
		diff = (leaves_allowed - leaves).toFixed(0);
		if(diff>=0)
		{
			cal.innerHTML += "<br/>No. of further leaves you can take: <b>"+diff+"<\/b>";
		}
		else
		{
			diff = -diff;
			cal.innerHTML +="<br/>Current no. of leaves = "+leaves+"<br/>";
			cal.innerHTML += "<br/>You are running short of the cut-off attendance this month. You took <b>"+diff+"<\/b> more leave(s) than allowed!";
		}
	},
	getLog: function()
	{
	 	var cal = document.getElementById("cal");
		cal.innerHTML = "";
		var attended_days =0;
		var off_days = 0;
		var days_in_month=Date.getDaysInMonth(current_day.getYear(),current_day.getMonth());
		var html = [];
		html.push("<div id='log'>");
		html.push("<h2>Attendance Log for "+current_day.getMonthName()+"</h2>");

		for(i=0;i<events.length;i++)
		{
			event = events[i];
			html.push("<div class='evententry'>");
			html.push(event.getTimes()[0].endTime.substring(8,10)+" "+current_day.getMonthName()+" "+current_day.toString('yyyy'));
			event_title = event.getTitle().getText();
			if(event_title=='off')
			{
				event_status = "College was Off";
				off_days++;
			}
			if(event_title =='went')
			{
				event_status = "Went to College";
				attended_days++;
			}
			if(event_title == 'notwent')
			{
				event_status = "Took a Leave";
			}
			html.push(" - "+event_status);
			html.push('</div>');
		}
		var future_days = days_in_month - events.length;
		html.push("<br/>No. of Days Attended College this Month = "+attended_days);
		html.push("<br/>Percentage Attendance for this Month = "+ProxyCal.getPercentage(attended_days,off_days,future_days,days_in_month)+"%");
		html.push("</div>");
		cal.innerHTML = html.join('');
	},
	
	//main function that displays the calendar
	displayCalendar: function(){
		var cal = document.getElementById("cal");
		var today = Date.today().setTimezoneOffset(+530);
		var no_of_days_attended=0; //No of days attended college this month
		var no_of_days_off = 0; //No. of days college was off
		var no_of_leaves = 0; //No. of days took leave from college
		var no_of_days_in_future = 0; //No. of days left in this month
		var html= [];
		events_to_add.length = 0;
		ProxyCal.generateLoader("Loading "+current_day.getMonthName()+" Calendar...");
		var firstday = Date.parse(current_day.getMonthName()).getDayName();
		html.push("<table id='calendar' cellspacing='0' cellpadding='0' summary='This month's calendar'><caption><a href='javascript:ProxyCal.getPreviousMonth();' title='previous month' class='nav'>&laquo;<\/a> "+current_day.getMonthName()+" "+current_day.toString("yyyy")+" <a href='javascript:ProxyCal.getNextMonth();' title='next month' class='nav'>&raquo;<\/a> <\/caption><tr><th scope='col' abbr='Sunday' title='Sunday'>S<\/th><th scope='col' abbr='Monday' title='Monday'>M<\/th><th scope='col' abbr='Tuesday' title='Tuesday'>T<\/th><th scope='col' abbr='Wednesday' title='Wednesday'>W<\/th><th scope='col' abbr='Thursday' title='Thursday'>T<\/th><th scope='col' abbr='Friday' title='Friday'>F<\/th><th scope='col' abbr='Saturday' title='Saturday'>S<\/th><\/tr><tr>");
		var count=0;
		var today_event=null;
		var offset = Date.getDayNumberFromName(firstday);
		var days_in_month=Date.getDaysInMonth(current_day.getYear(),current_day.getMonth());
		for(var j=offset;j!=0;j--){
			html.push("<td><\/td>");
			count++;
		}
		var eventno=0;
		var event = [];
		for(var i=1;i<=days_in_month;i++)
		{
			//alert(eventno);
			flag=0;
			temp_date = i;
			var event = events[eventno];
			if(temp_date<10)
			{
				temp_date = "0"+String(temp_date);
			}
			if(count==7)
			{
				html.push("<\/tr><tr>");
				count=0;
			}
			if(event)
			{
				if(parseInt(event.getTimes()[0].endTime.substring(8,10))==today.getDate() && event.getTimes()[0].endTime.substring(0,7)==today.toString("yyyy-MM"))
				{
					today_event = event;
				}
				if(event.getTimes()[0].endTime.substring(8,10)==temp_date && event.getTimes()[0].endTime.substring(0,7)==current_day.toString("yyyy-MM"))
				{
					//Giving the appropriate color to each date of the month ( according to the status i.e. went, notwent or off )
					if(event.getTitle().getText()=="went")
					{
						html.push("<td class='went'><a title="+i+" href='javascript:ProxyCal.changeEventPopup("+i+");'>"+i+"<\/a><\/td>");
						no_of_days_attended++;
					}
					else if(event.getTitle().getText()=="notwent")
					{
						html.push("<td class='notwent'><a title="+i+" href='javascript:ProxyCal.changeEventPopup("+i+");'>"+i+"<\/a><\/td>");
						no_of_leaves++;
					}
					else if(event.getTitle().getText()=="off")
					{
						html.push("<td class='off'><a title="+i+" href='javascript:ProxyCal.changeEventPopup("+i+");'>"+i+"<\/a><\/td>");
						no_of_days_off++;
					}
					flag=1;
					if(eventno<(events.length-1))
					{
						eventno++;
					}
				}
			}
			// For setting the default updates for the current month
			if(flag == 0)
			{
				if(current_day.getMonth()==today.getMonth() && current_day.getYear()==today.getYear())
				{
					if(i<today.getDate())
					{
						html.push("<td class=''><a href='javascript:ProxyCal.addEventPopup("+i+")'>"+i+"<\/a><\/td>");
						events_to_add.push(i.toString());
					}
					else if(i==today.getDate())
					{
						html.push("<td class=''><a href='javascript:ProxyCal.addEventPopup("+i+")'>"+i+"<\/a><\/td>");
					}
					else
					{
						html.push("<td class=''>"+i+"<\/td>");
						no_of_days_in_future++;
					}
				}
				else if(current_day.getMonth()<today.getMonth() && current_day.getYear()<=today.getYear())
				{
					html.push("<td class=''><a href='javascript:ProxyCal.addEventPopup("+i+")'>"+i+"<\/a><\/td>");
				}
				else
				{
					html.push("<td class=''>"+i+"<\/td>");
				}
			}
			count++;
		}
		html.push("<\/table>");
		cal.innerHTML=html.join('');
		cal.innerHTML+="<br/><br/><h3>Today is "+today.getDate()+" "+today.getMonthName()+" "+today.toString("yyyy")+".";
		if(today_event)
		{
			cal.innerHTML+="Your status for today is ";
			if(today_event.getTitle().getText()=='went')
			{
				cal.innerHTML+="<b><font color='#50ee5a'>Went<\/font><\/b>";
			}
			if(today_event.getTitle().getText()=='notwent')
			{
				cal.innerHTML+="<b><font color='#ed5a2e'>Took a Leave<\/font><\/b>";
			}
			if(today_event.getTitle().getText()=='off')
			{
				cal.innerHTML+="<b><font color='#eedd00'>College was Off<\/font><\/b>";
			}
		 	cal.innerHTML+=".<br/><a href='javascript:ProxyCal.changeEventPopup("+today.getDate()+");'>Change Status?<\/a><br/>";

		}
		else
		{
			cal.innerHTML+="<a href='javascript:ProxyCal.addEventPopup("+today.getDate()+")'>Set your Status for Today<\/a>";
		}
		cal.innerHTML+="<br/>Current Attendance for this month = <b>"+ProxyCal.getPercentage(no_of_days_attended,no_of_days_off,no_of_days_in_future,days_in_month)+" % <\/b>";
		cal.innerHTML+="<br/>Cutoff Percentage: <b>"+cutoff+" %<\/b>";
		cal.innerHTML+="<br/>No. of days you attended college this month: <b> "+no_of_days_attended+"<\/b>";
		ProxyCal.calcAvailableLeaves(no_of_days_attended,no_of_days_off,no_of_days_in_future,days_in_month,no_of_leaves);
		ProxyCal.addEventsInBackground();
	},
	getFeed: function(){
		var cal = document.getElementById("cal");
		ProxyCal.generateLoader('Loading Settings...');
		var feedUri = 'http://www.google.com/calendar/feeds/default/allcalendars/full';
		var flag=0;
		var callback = function(result) {
	  	var entries = result.feed.entry;
	  	calendars = entries;
	  	for (var i = 0; i < entries.length; i++) {
	    	var calendarEntry = entries[i];
	    	var calendarTitle = calendarEntry.getTitle().getText();
				if(calendarTitle == "ProxyCal")
					flag=1;
			}
			if(flag == 1)
			{
				if(!calendarId)
					calendarId = ProxyCal.getCalendarId();
				ProxyCal.initSettings();
				ProxyCal.getEvents();
			}
			else
			{
				generateLoader("Creating ProxyCal Calendar...");
				createCalendar();
			}
		};
		// Error handler to be invoked when getFeed() produces an error
		var handleError = function(error) {
			_run();
		};
		calendarService.getEventsFeed(feedUri, callback, handleError);
	},
	initSettings: function(){
	if(calendarId)
		{
			//write an ajax reauest to getsettings.php here
		}
	}
};

google.setOnLoadCallback(ProxyCal._run);