
/* Loads the Google data JavaScript client library */
google.load("gdata", "1");

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
  loadDeveloperCalendar();
}


function loadDeveloperCalendar() {
/**
 * Loads the Google Developers Event Calendar
 */
      loadCalendarByAddress('justinrosen19%40gmail.com');
	  
//https://www.google.com/calendar/feeds/justinrosen19%40gmail.com/public/basic
}


function padNumber(num) {
/**
 * Adds a leading zero to a single-digit number... for displaying the dates.
 */
      if (num <= 9) {
        return "0" + num;
      }
      return num;
}

 
function loadCalendarByAddress(calendarAddress) {
/**
 * 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
 */

      var calendarUrl = 'http://www.google.com/calendar/feeds/' +calendarAddress + '/public/full';
      loadCalendar(calendarUrl);
}

  
function loadCalendar(calendarUrl) {
/**
 * 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
 
 */
      var service = new
          google.gdata.calendar.CalendarService('GoogleInc-jsguide-1.0');
      var query = new google.gdata.calendar.CalendarEventQuery(calendarUrl);
      query.setOrderBy('starttime');
      query.setSortOrder('ascending');
      query.setFutureEvents(true);
      query.setSingleEvents(true);
      query.setMaxResults(10);

      service.getEventsFeed(query, listEvents, handleGDError);
      service.getEventsFeed(query, listGameEvent, handleGDError);
}


function handleGDError(e) {
/**
 * 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
 */
  //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());
  }
}
function Opponent(searchname, name) {
    this.searchname = searchname;
    this.name = name;
}
function Findmonth (month){//function to take the month number from google for the gameInfo box date title
    if      (month==1)  {var gameMonth="January";}
    else if (month==2)  {gameMonth="February";}
    else if (month==3)  {gameMonth="March";}
    else if (month==4)  {gameMonth="April";}
    else if (month==5)  {gameMonth="May";}
    else if (month==6)  {gameMonth="June";}
    else if (month==7)  {gameMonth="July";}
    else if (month==8)  {gameMonth="August";}
    else if (month==9)  {gameMonth="September";}
    else if (month==10) {gameMonth="October";}
    else if (month==11) {gameMonth="November";}
    else if (month==12) {gameMonth="December";}
    return (gameMonth);
}
function Changetime (hours){
    if (hours > 12) {
        hours = hours - 12;
        chHours=hours;}
    else{chHours=hours;}
        return chHours;
    
}
function Tag (hours){
    if (hours < 12){tag="AM";}
    else {tag="PM";}
    return tag;
}
function Day (num){
    if (num==0){var day="Sunday";}
    else if (num==1){day="Monday";}
    else if (num==2){day="Tuesday";}
    else if (num==3){day="Wednesday";}
    else if (num==4){day="Thursday";}
    else if (num==5){day="Friday";}
    else if (num==6){day="Saturday";}
    return (day);
}


function listGameEvent(feedRoot) {

  var entries = feedRoot.feed.getEntries();
  var len = entries.length;
  var gameFound=false;
   /* parsing events for next gam */
  var southgateDiv = document.getElementById('southgateGame');
  var vsDiv = document.getElementById('vs');
  var gameTitleDiv= document.getElementById('gameTopRow');
  var opponentDiv = document.getElementById('opponent');
  var prepNameDiv = document.getElementById('prepName');
  var oppNameDiv = document.getElementById('oppName');
  var gameInfoDiv = document.getElementById('gameInfo');
  for (var g=0; (g < len) && gameFound==false; g++) {
            //create array for the teams we might play, then fill array with team object function adding properties
            var teams = new Array();
            teams[0] = new Opponent ('wyandotte', 'Wyandotte');
            teams[1] = new Opponent ('dexter', 'Dexter Prep');
            teams[2] = new Opponent ('wolves', 'Bay City Wolves');
            teams[3] = new Opponent ('northern', 'Walled Lake Northern');
            teams[4] = new Opponent ('central', 'Walled Lake Central');
            teams[5] = new Opponent ('warrior', 'Woodhaven Warrior Prep');
            teams[6] = new Opponent ('royal', 'Royal Oak');
            teams[7] = new Opponent ('trenton', 'Trenton');
            teams[8] = new Opponent ('berkley', 'Berkley');
            teams[9] = new Opponent ('dow', 'Midland Dow');
            teams[10] = new Opponent ('jackson', 'Jackson Titan Prep');
			teams[11] = new Opponent ('leafs', 'Woodhaven Leafs 96');
			teams[12] = new Opponent ('jefferson', 'Monroe Jefferson');
			teams[13] = new Opponent ('unified', 'Taylor Unified');
			teams[14] = new Opponent ('huron', 'New Boston Huron');
			teams[15] = new Opponent ('richard', 'Gabriel Richard');
			teams[16] = new Opponent ('jags', 'Allen Park Jags');
			teams[17] = new Opponent ('cabrini', 'Cabrini');
			teams[18] = new Opponent ('monroe', 'Monroe');
			teams[19] = new Opponent ('pinckney', 'Pinckney');
			teams[20] = new Opponent ('salem', 'Salem');
			teams[21] = new Opponent ('blanc', 'Grand Blanc');
			teams[22] = new Opponent ('point south', 'Grosse Point South');
			teams[23] = new Opponent ('canton', 'Canton Chiefs');
			teams[24] = new Opponent ('shamrock', 'Shamrock Prep');
			teams[25] = new Opponent ('milford', 'Milford');
			teams[26] = new Opponent ('howell', 'Howell');
			teams[27] = new Opponent ('thunder', 'Bay Area Thunder');
			teams[28] = new Opponent ('northville', 'Northville');
			teams[29] = new Opponent ('brighton', 'Brighton');
			teams[30] = new Opponent ('lakeland', 'Lakeland');
			teams[31] = new Opponent ('anchor', 'Anchor Bay');
			teams[32] = new Opponent ('lanse', 'Lanse Creuse');
			teams[33] = new Opponent ('hartland', 'Hartland Blue Prep');
			teams[34] = new Opponent ('lyon', 'South Lyon Silver Prep');
			//add new teams here, but must change 2 values noted later in code
	  var checkEntry = entries[g];
	  var checkTitle=checkEntry.getTitle().getText();
	  var isTitle=checkTitle.toLowerCase();
          var gameTime = null;
          var gameDate = null;
          var times = checkEntry.getTimes();
          if (times.length > 0) {
            gameTime = times[0].getStartTime();
            gameDate = gameTime.getDate();
            }
          var gdateString = Findmonth((gameDate.getMonth() + 1)) + " " + gameDate.getDate();
          var regGameHours = gameDate.getHours();
          var gameYear= gameDate.getFullYear();
          var gameDay= gameDate.getDay();
          var location = checkEntry.getLocations()[0].getValueString();
          if (!gameTime.isDateOnly()) {
            gdateString  = Day(gameDay) + " " +gdateString +  ", " + gameYear +"  @  " + Changetime(regGameHours) + ":" +
            padNumber(gameDate.getMinutes()) + " " + Tag(regGameHours);
          }
 
          var game = /game/gi;
	  //need to convert isTitle here to lowercase for parsing
	  var gameCheck=isTitle.search(game);
			if ((gameCheck == -1) &&(g==len)) {
				//then print "there are no upcoming games"
                                
                                document.write('there are no games');
			}
			else if (gameCheck != -1){
                            var nextGameTitle= checkTitle;
                            gameFound=true;
                            found=false;
                            for (n=0; n <35 && found==false; n++){ //need to add 1 to n<## if a team object is added to array
                                var theTeam=teams[n];
                                var isTeam=theTeam.searchname;
                                //var teamSearch= new String(isTeam);
                                var isNextGame = nextGameTitle.toLowerCase();
                                var teamCheck = isNextGame.search(isTeam);

                                    if (teamCheck != -1) {
                                        var opponentName = teams[n].name;
                                        found=true;
                                        gameTitleDiv.innerHTML="Next Game";
                                        southgateDiv.innerHTML="<img src='http://www.southgatejvhockey.com/images/opponents/southgate.png' />";
                                        vsDiv.innerHTML="<h1>VS</h1>";
                                        prepNameDiv.innerHTML="Southgate Prep";
                                        opponentDiv.innerHTML="<img src='http://www.southgatejvhockey.com/images/opponents/" +theTeam.searchname+".png'/>"
                                        oppNameDiv.innerHTML = theTeam.name;
                                        gameInfoDiv.innerHTML = gdateString + "<br/>" + location;
                                    }
                                    else if((teamCheck == -1) && (n>33)) { //need to add 1 to n># if team object is added to array
                                        opponentDiv.innerHTML="Cant find Team";
                                    }                               
                            }
                    }
        }
  /*parsing for next game ends here */ 
}

function listEvents(feedRoot) {
  var entries = feedRoot.feed.getEntries();
  var eventDiv = document.getElementById('events');
  if (eventDiv.childNodes.length > 0) {
    eventDiv.removeChild(eventDiv.childNodes[0]);
  }	  
  /* create a new unordered list */
  var ul = document.createElement('ul');
  /* set the calendarTitle div with the name of the calendar */
  document.getElementById('calendarTitle').innerHTML = 
    "Upcoming Events" ;
  /* loop through each event in the feed */
  var len = entries.length;
  for (var i = 0; i < len; i++) {
    var entry = entries[i];
    var title = entry.getTitle().getText();
    var startDateTime = null;
    var startJSDate = null;
    var times = entry.getTimes();
    if (times.length > 0) {
      startDateTime = times[0].getStartTime();
      startJSDate = startDateTime.getDate();
    }
    var entryLinkHref = null;
    if (entry.getHtmlLink() != null) {
      entryLinkHref = entry.getHtmlLink().getHref();
    }

    var regHours = startJSDate.getHours();
		
    var dateString = (startJSDate.getMonth() + 1) + "/" + startJSDate.getDate();
    if (!startDateTime.isDateOnly()) {			
      dateString += " " + Changetime(regHours) + ":" +
          padNumber(startJSDate.getMinutes()) + " " + Tag(regHours);
    }	
    var li = document.createElement('li');  
      li.appendChild(document.createTextNode(title + ' - ' + dateString));
	
    /* append the list item onto the unordered list */
    ul.appendChild(li);
  }
  eventDiv.appendChild(ul);
}

google.setOnLoadCallback(init);
//-->
