

//Public Feed
/* Loads the Google data JavaScript client library */
try{
google.load("gdata", "1.x");
}catch(err){
if(err=="TypeError: Object #<Object> has no method 'load'"){
setTimeout(function(){alert("Fail to load Google Calendar API! \n\nMaybe reload the page will help?")},100)
}
}

var myService;
//var feedLocation="developer-calendar@google.com"
var feedLocation="E-MAIL HERE"
var feedUrl = "https://www.google.com/calendar/feeds/"+feedLocation+"/public/full";

function setupMyService() {
  myService = new google.gdata.calendar.CalendarService('exampleCo-exampleApp-1');
}

function getMyFeed() {
var txt=prompt("Enter you email or click cancel to cancel:\n\nFor example, if you want to import Google Developer Events Calendar, then type in:\ndeveloper-calendar@google.com",feedLocation)
if(!txt||txt==""){
return false
}else{
window.noti=webkitNotifications.createNotification("/b_icon.png","Please wait,", "while data are fetching...")
noti.show();
console.warn("Feteching data from \""+txt+"\"")
window.feedLocation=txt
window.feedUrl = "https://www.google.com/calendar/feeds/"+feedLocation+"/public/full";
}
  setupMyService();
 
  myService.getEventsFeed(feedUrl, handleMyFeed, handleError);
}

var err=0
var totalwritein=0
function handleMyFeed(myResultsFeedRoot) {
totalwritein=0
noti.cancel()
for(i=0;i<myResultsFeedRoot.feed.getEntries().length;i++){
try{
var item=myResultsFeedRoot.feed.getEntries()[i];
var title=item.getTitle().getText()
//GET DATA
    var startDateTime = null;
    var startJSDate = null;
    var times = item.getTimes();
    if (times.length > 0) {
      startDateTime = times[0].getStartTime();
      startJSDate = startDateTime.getDate();
    }
    var entryLinkHref = null;
    if (item.getHtmlLink() != null) {
      entryLinkHref = item.getHtmlLink().getHref();
    }


var date=new Date(startJSDate)

//Write local
if((date.getMonth()+1)==(new Date().getMonth()+1)){
if(localStorage["todo"+(date.getMonth()+1)+date.getDate()]==null||(localStorage["todo"+(date.getMonth()+1)+date.getDate()]!=null&&confirm("A todo is saved in date "+date.getDate()+"?\nDo you want to overwirte?"))){
totalwritein++
localStorage["todo"+(date.getMonth()+1)+date.getDate()]=title+((!startDateTime.isDateOnly())?(" - Starts at "+date.getHours()+":"+date.getMinutes()):"")+" ("+myResultsFeedRoot.feed.getTitle().getText()+")";
}
}



}catch(e){err++;console.log(e)}
}

if(err!=0){
alert(err+" errors has occured!")
}
if(totalwritein>=0){
alert(totalwritein+" events are successfully imported to Cool Clock's calendar!")
}
}

function handleError(e) {
noti.cancel()
  alert("There was an error when loading account!");
//  alert(e.cause ? e.cause.statusText : e.message);
window.open(feedUrl,"_blank")
}


//==============Private Feed===============

function getMyselfFeed(){
//var url="https://www.google.com/calendar/feeds/default/private/embed?toolbar=true&max-results=50"
var url="https://calendar.google.com/feeds/default/private/embed?toolbar=true&max-results=50"
xmlhttp=new XMLHttpRequest();
window.noti=webkitNotifications.createNotification("/b_icon.png","Please wait,", "while data are fetching...")
noti.show();
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200){
 feed=xmlhttp.responseXML.documentElement
 entry=feed.getElementsByTagName("entry");
 console.log("Fetched data from Google Calendar")
 success=0
importMyselfFeed();
noti.cancel()
if(success==0){
window.noti=webkitNotifications.createNotification("/b_icon.png","No entry found in this month!", "There isn't any entry in this month for "+feed.getElementsByTagName("email")[0].firstChild.nodeValue+" .")
noti.show();
return false
}else{
window.noti=webkitNotifications.createNotification("/b_icon.png","Import successful!", success+" events are successfully imported to Cool Clock's calendar from "+feed.getElementsByTagName("email")[0].firstChild.nodeValue+" .")
}
noti.show();
setTimeout(function(){noti.cancel()},7000)
window.open("calendarrecords.html","_new","toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,copyhistory=no,width=800,height=600,left=10,top=10");

}else if(xmlhttp.readyState==4){

noti.cancel()
if(xmlhttp.status==401){
window.noti=webkitNotifications.createNotification("/b_icon.png","Import not success!", "Please make sure that you have logged-in in Google Calendar."+" (Status:"+xmlhttp.status+")")
}else if(xmlhttp.status==0){
window.noti=webkitNotifications.createNotification("/b_icon.png","Can not contact Google Calendar!", "Please make sure there is an internet connection.")
}else{
window.noti=webkitNotifications.createNotification("/b_icon.png","Import not success!", "An error occured when fetching data. Please make sure that you have logged in."+" (Status:"+xmlhttp.status+")")
}
noti.show();
return false
}
}
xmlhttp.open("GET",url,true);
xmlhttp.send();

}

function importMyselfFeed(){
for(i=0;i<entry.length;i++){
var data=entry[i].getElementsByTagName("title")[0].firstChild.nodeValue
var datatxt=entry[i].childNodes[6].getAttribute("startTime")
var datatime=new Date(datatxt)
var d=new Date()
if(datatime.getYear()!=d.getYear()){
continue
}
if(datatime.getMonth()!=d.getMonth()){
continue
}
if(localStorage["todo"+(d.getMonth()+1)+datatime.getDate()]!=null){
if(!confirm("Do you want to replace to-do for "+(d.getMonth()+1)+"/"+datatime.getDate()+"?")){
continue
}
}
localStorage["todo"+(d.getMonth()+1)+datatime.getDate()]=data+" (From Google Calendar)"
success++
}
}


//==============Background Private Feed===============

function bgFeed(){
//var url="https://www.google.com/calendar/feeds/default/private/embed?toolbar=true&max-results=50"
var url="https://calendar.google.com/feeds/default/private/embed?toolbar=true&max-results=50"
xmlhttp=new XMLHttpRequest();

xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200){
 feed=xmlhttp.responseXML.documentElement
 entry=feed.getElementsByTagName("entry");
 console.group("Fetched data from Google Calendar")
 success=0
bgImportMyselfFeed();

if(success==0){
console.log("No entry found.")
console.groupEnd()
return false
}else{
console.log("Import successful.")
console.groupEnd()
}

}else if(xmlhttp.readyState==4){

if(xmlhttp.status==401){
console.log("Import not success.")
}else if(xmlhttp.status==0){
console.log("Can not contact Google Calendar.")
}else{
console.log("Import not success.")
}
console.groupEnd()
return false
}
}
xmlhttp.open("GET",url,true);
xmlhttp.send();

}

function bgImportMyselfFeed(){
for(i=0;i<entry.length;i++){
var data=entry[i].getElementsByTagName("title")[0].firstChild.nodeValue
var datatxt=entry[i].childNodes[6].getAttribute("startTime")
var datatime=new Date(datatxt)
var d=new Date()
if(datatime.getYear()!=d.getYear()){
continue
}
if(datatime.getMonth()!=d.getMonth()){
continue
}
if(localStorage["todo"+(d.getMonth()+1)+datatime.getDate()]!=null){
console.log("Replaced to-do for "+(d.getMonth()+1)+"/"+datatime.getDate())
}
localStorage["todo"+(d.getMonth()+1)+datatime.getDate()]=data+" (From Google Calendar)"
success++
}
}