/*-------------------------------------------------------------------------*/

function handleError(e) {
  alert("Someting went wrong, pleaase try reloading the page");
  alert(e.cause ? e.cause.statusText : e.message);
}
/*---------------------------------------------------------------------*/
function setupTOFcalService() {
  TOFcalService = new google.gdata.calendar.CalendarService('exampleCo-exampleApp-1');
}
/*---------------------------------------------------------------------*/
function getTOFcalFeed() {
  setupTOFcalService();

  sm = new Date();
  TOFcalURL = TOFcalURL + '&start-min=' + sm.toStartMin();

  TOFcalService.getEventsFeed(TOFcalURL, ProcessTOFcal, handleError);
  return(1);
}
/*---------------------------------------------------------------------*/

PRINT = ( function( regel ) { divcontent +=  regel ;} );

/*---------------------------------------------------------------------*/

function ProcessTOFcal( feedRoot ) {
  var currentyear = 0;
  

  sm = new Date();

  //PRINT ( '<center><img src="img/toflogo30.gif" style="height: 106px;width: 105px;border: 0px;" /></center>');
  PRINT ( '<h5> Gigs ' + feedRoot.feed.getTitle().getText()  );
  PRINT ( ' dd. ' + feedRoot.feed.getUpdated().getValue().getDate().toLdate() + '</h5>' );
  

  // Obtain the array of CalendarEventEntry
  var entries = feedRoot.feed.entry;    
  
  for (var i = 0; i < entries.length; i++ ) {
    thisentry 	 = entries[i];

    estartdate 	 = thisentry.getTimes()[0].getStartTime().getDate(); 
    eenddate	 = thisentry.getTimes()[0].getEndTime().getDate(); 
    
    entryyear = estartdate.getFullYear();	
    if ( currentyear < entryyear ){
	PRINT( '<h3>' + entryyear + '</h3>' );
	currentyear = entryyear;
    }	 	

    printEvent( thisentry, estartdate, eenddate );
  }

document.getElementById( "uitkomst").innerHTML = divcontent;
//alert( divcontent );
return(0);
}

/*--------------------------------------------------------------------*/
function isOneWholeDay( estartdate, eenddate )
{
var iswhole = false;
if ( estartdate.getHours() == 0 && eenddate.getHours() == 0 ){
  if ( estartdate.getMinutes() == 0 && eenddate.getMinutes() == 0 ){
    if ( estartdate.getSeconds() == 0 && eenddate.getSeconds() == 0 ){
       var oneday =  24 * 3600 * 1000;
       diftime = eenddate.getTime() - estartdate.getTime();
       if ( diftime < ( oneday + 2000 ) && diftime > (oneday - 2000) )return( true );	
    }
  }
}
return( false );
}

/*--------------------------------------------------------------------*/
function escapeDescription( input, offset )
{
var output="";
var o,i,ic,oc;

for ( i = 0, oc = offset ; i < input.length;++i){
      ic = input.substr(i,1);
  
      if ( oc > 75 ){
		output = output + '\n '; //lf + space
		oc = 1;
	}

	switch( ic ){
		case '\\':
		case ',':
			output = output + '\\' + ic;
			++oc;++oc;
			break;
		case '\n':
			output = output + '\\n';
			++oc; ++oc; 
			break;
		case '\r':
			output = output + '\\r';
			++oc; ++oc; 
			break;
		default:
			output = output + ic;
			++oc;
			break;
	 }
 }
			
return( output );
}

/*--------------------------------------------------------------------*/

function quoted_printable_encode(str) {
    // +   original by: Theriault
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +   improved by: Theriault
    // *     example 1: quoted_printable_encode('a=b=c');
    // *     returns 1: 'a=3Db=3Dc'
    // *     example 2: quoted_printable_encode('abc   \r\n123   \r\n');
    // *     returns 2: 'abc  =20\r\n123  =20\r\n'
    // *     example 3: quoted_printable_encode('0123456789012345678901234567890123456789012345678901234567890123456789012345');
    // *     returns 3: '012345678901234567890123456789012345678901234567890123456789012345678901234=\r\n5'

    // RFC 2045: 6.7.2: Octets with decimal values of 33 through 60 (bang to less-than) inclusive, and 62 through 126 (greater-than to tilde), inclusive, MAY be represented as the US-ASCII characters
    // PHP does not encode any of the above; as does this function.
    // RFC 2045: 6.7.3: Octets with values of 9 and 32 MAY be represented as US-ASCII TAB (HT) and SPACE characters, respectively, but MUST NOT be so represented at the end of an encoded line
    // PHP does not encode spaces (octet 32) except before a CRLF sequence as stated above. PHP always encodes tabs (octet 9). This function replicates PHP.
    // RFC 2045: 6.7.4: A line break in a text body, represented as a CRLF sequence in the text canonical form, must be represented by a (RFC 822) line break
    // PHP does not encode a CRLF sequence, as does this function.
    // RFC 2045: 6.7.5: The Quoted-Printable encoding REQUIRES that encoded lines be no more than 76 characters long. If longer lines are to be encoded with the Quoted-Printable encoding, "soft" line breaks must be used.
    // PHP breaks lines greater than 76 characters; as does this function.
    var hexChars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'],
    RFC2045Encode1IN = / \r\n|\r\n|[^!-<>-~ ]/gm,
    RFC2045Encode1OUT = function (sMatch) {
        // Encode space before CRLF sequence to prevent spaces from being stripped
        // Keep hard line breaks intact; CRLF sequences
        if (sMatch.length > 1) {
            return sMatch.replace(' ', '=20');
        }
        // Encode matching character
        var chr = sMatch.charCodeAt(0);
        return '=' + hexChars[((chr >>> 4) & 15)] + hexChars[(chr & 15)];
    },
    // Split lines to 75 characters; the reason it's 75 and not 76 is because softline breaks are preceeded by an equal sign; which would be the 76th character.
    // However, if the last line/string was exactly 76 characters, then a softline would not be needed. PHP currently softbreaks anyway; so this function replicates PHP.
    RFC2045Encode2IN = /.{1,72}(?!\r\n)[^=]{0,3}/g,
    RFC2045Encode2OUT = function (sMatch) {
        if (sMatch.substr(sMatch.length - 2) === '\r\n') {
            return sMatch;
        }
        return sMatch + '=\r\n';
    };
    str = str.replace(RFC2045Encode1IN, RFC2045Encode1OUT).replace(RFC2045Encode2IN, RFC2045Encode2OUT);
    // Strip last softline break
    return str.substr(0, str.length - 3);
}

/*--------------------------------------------------------------------*/
function printEvent( thisentry, estartdate, eenddate )
{
    estarttime 	= estartdate.toLtime(); 
    eendtime	= eenddate.toLtime(); 

    estart 	 	= estartdate.toLdate( -1 );
    eeend 	 	= eenddate.toLdate( -1 );

    wholeday      = isOneWholeDay( estartdate, eenddate )
   
    eventTitle 	= thisentry.getTitle().getText();
    eventContent  = thisentry.getContent().getText();
    
    eventLocation = thisentry.getLocations()[0].getValueString();

    eventSequence = thisentry.getSequence();
    eventUid      = thisentry.getUid();
    eventUpdated  = thisentry.getUpdated();
	
    iTitle       = encodeURIComponent( quoted_printable_encode( eventTitle ) );
    iContent     = encodeURIComponent( quoted_printable_encode(eventContent));
    iLocation    = encodeURIComponent( eventLocation );
    iSequence    = encodeURIComponent( thisentry.getSequence().getValue());
    iUid         = encodeURIComponent( quoted_printable_encode( thisentry.getUid().getValue() ));
    iUpdated     = encodeURIComponent( thisentry.getUpdated().getValue().getDate().toICSUTC() ); 

    if ( !(wholeday) ){
      iStart = estartdate.toICSUTC();
      iEnd   = eenddate.toICSUTC();
    }else{
      iStart = estartdate.tofullday();
      iEnd   = eenddate.tofullday();       
    }		
	
    iref = 'gapi2ics.php?';
    iref = iref + 'what=' + iTitle;
    
    iref = iref + '&mod=' + iUpdated; 
    iref = iref + '&sequence=' + iSequence + '&uid=' + iUid ;
    iref = iref + '&start=' + iStart + '&end=' + iEnd ; 
    iref = iref + '&info=' + iContent + '&where=' + iLocation;

    PRINT('<div class="entryclass"><span class="entryclass">' + estart + '</span>' );

    if ( !(wholeday) ){
      PRINT( '<span class="entryclass" style="margin-left: 4px;">' + estarttime + ' - ' + eendtime + '</span>');
    }		

    PRINT('<span class="entryclass" style="margin-left: 10px;">' + eventTitle +'</span>');
    PRINT('<span class="entryclass" style="float: right; font-size: 8px; font-weight: normal;">');
    PRINT('<a href="' + iref + '" target="_blank">');
    PRINT( '<img src="ical.png" class="aicon" title="export gig in iCal" ></a></span>');
    PRINT('<br>');

    PRINT( '<div style="margin-left: 10px; clear: both;"><a href="http://maps.google.com/maps?hl=nl&q=' + encodeURI( eventLocation ));
    PRINT( '" target="_blank">');
    PRINT( '<img src="location.png" class="aicon" title="Google maps"></a>' +  eventLocation + '</div>');

    PRINT('<div style="margin-left: 10px;">');
    PRINT('<img src="info.png" class="aicon">' );
    PRINT( eventContent.replace(/\n/g,"<br>").replace(/<br><br>/g,"<br>").replace("<br>"," ") ); 
    PRINT('</div>');
    PRINT('</div>');
}

