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

//get domain name for calendar links
var myDomain = window.location.hostname;

//check for calendar request
function calInit() {
				
				
	//Get contents of page
	var calReplaceMe = $("#center2").html();
	
	//see if #calCont exists
	if ($("#calCont").html() != null){
		/*ORIGINAL JS CODE. NOW USING PHP WITHIN WORDPRESS LOOP SINCE IT PROCESSES BEFORE CONTENT IS LOADED
					//find start and stop indices of calendar string
					var strStart = calReplaceMe.indexOf("{CALENDAR,");
					var strStop = calReplaceMe.indexOf("}",strStart);
					
					
					//get calendar string from calendar string
					var calString = calReplaceMe.substring(strStart,strStop+1);
					//remove white space
					var calStringStrip = calString.replace(" ","");
					//remove {CALENDAR,
					calStringStrip = calStringStrip.replace("{CALENDAR,","");
					//remove } and we have the calendar category left
					var calCategory = calStringStrip.replace("}","");
					
					//replace main content with modified content
					$("#center2").html(calReplaceMe);
		*/
		
				//get calendar category printed to the "rel" attribute in wordpress loop
				calCategory = $("#calCont").attr("rel");
				//replace calendar string with div for event list
				$("#calCont").html("<div class='calLeft'><span class='calHeader'>"+calCategory+" EVENTS: </span><span class='fullCalLink'><a href='http://"+myDomain+"/wp-content/themes/golf/fullCal.php' class='fullCal'>See All</a></span></div><div id='CalEvents'><img src='http://"+myDomain+"/wp-content/themes/golf/images/loading.gif'></div>");
				
				
		
		 // init the Google data JS client library with an error handler
		 google.gdata.client.init(handleGDError);
		 //get event list based on calendar string
		 loadDeveloperCalendar(calCategory);
			

	}//end if
				
				
				
	  
}//end function calInit



function loadDeveloperCalendar(myCal) {
	var loadMe;

switch(myCal)
{
	case 'GOLF':
	  loadMe='thegreenscc.com_fpsme5m416nh31eq2nhcok1euo@group.calendar.google.com';
	  // alert("Golf");
	  break;
	case 'TENNIS':
	  loadMe='thegreenscc.com_jluiusi2l4dpdhiqd2g5hfm2d0@group.calendar.google.com';
	  // alert("Tennis");
	   break;
	
	 break;
	case 'SOCIAL':
	 loadMe='thegreenscc.com_c9hpige197t4upp4clqv3ek4tk@group.calendar.google.com';
		//alert("Social");
	  break;
	case 'DINING':
	 loadMe='thegreenscc.com_do9pki1htdd34rgbe115s6hop4@group.calendar.google.com';
	 //	alert("Dining");
	  
	default:
	  //alert("need calendar");
	}
  loadCalendarByAddress(loadMe);
 // loadCalendarByAddress('developer-calendar@google.com');
}

/**
 * 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);
}

/**
 * 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('rsr-training');
  var query = new google.gdata.calendar.CalendarEventQuery(calendarUrl);
  query.setOrderBy('starttime');
  query.setSortOrder('ascending');
  query.setFutureEvents(true);
  query.setSingleEvents(true);
  query.setMaxResults(3);

  service.getEventsFeed(query, listEvents, 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 listEvents(feedRoot) {

  var entries = feedRoot.feed.getEntries();
 //document.write(entries);
  var eventDiv = document.getElementById('CalEvents');
  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 = 
    "<h3>Upcoming Events</h3>" */
  /* 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 timeString;
    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();
    }
	//alert(startJSDate.getDate());
	var day_name=new Array(7);
		day_name[0]="Sunday"
		day_name[1]="Monday"
		day_name[2]="Tuesday"
		day_name[3]="Wednesday"
		day_name[4]="Thursday"
		day_name[5]="Friday"
		day_name[6]="Saturday"
		
		var myDay = day_name[startJSDate.getDay()];
		myDay = myDay.substring(0,3) + ".";
		
		var month_name=new Array(12);
		month_name[0]="January"
		month_name[1]="February"
		month_name[2]="March"
		month_name[3]="April"
		month_name[4]="May"
		month_name[5]="June"
		month_name[6]="July"
		month_name[7]="August"
		month_name[8]="September"
		month_name[9]="October"
		month_name[10]="November"
		month_name[11]="December"
		
		var myMonth = month_name[startJSDate.getMonth()];
		myMonth = myMonth.substring(0,3) + ".";
		
		var myDayEnd = (startJSDate.getDate() % 10 == 1 && startJSDate.getDate() != 11 ? 'st' : (startJSDate.getDate() % 10 == 2 && startJSDate.getDate() != 12 ? 'nd' : (startJSDate.getDate() % 10 == 3 && startJSDate.getDate() != 13 ? 'rd' : 'th')));
		
		var myDaySup = document.createElement('sup');
			myDaySup.appendChild(document.createTextNode(myDayEnd));
			
		var myDateString = document.createElement('span');
			myDateString.setAttribute('class','calDateString');
			
    var dateString = " - "+ myDay +" "+ myMonth + " " + startJSDate.getDate();
	
			myDateString.appendChild(document.createTextNode(dateString));
			myDateString.appendChild(myDaySup);
	
    if (!startDateTime.isDateOnly()) {
		
			//Convert to standard time
			var ampm = "am";
			var mh = startJSDate.getHours();
			if(mh > 12) {
			mh = mh - 12; //standard hours
			ampm = "pm";
			}
			
      timeString = mh + ":" + 
          padNumber(startJSDate.getMinutes())  + ampm;
    }
	else{
		timeString = "";
	}
    var li = document.createElement('li');
	//Create substring of Title for formatting
	if (title.length > 23){
		title = title.substring(0,20) + "...";
	}
    /* if we have a link to the event, create an 'a' element */
	var br = document.createElement('br');
	var timeSpan = document.createElement('span');
		timeSpan.setAttribute('class','calTime');
	
	var titleSpan = document.createElement('span');
		titleSpan.setAttribute('class','calTitle');
	
	var dateSpan = document.createElement('span');
		dateSpan.setAttribute('class','calDate');
	
    if (entryLinkHref != null) {
      entryLink = document.createElement('a');
      entryLink.setAttribute('href', "http://"+myDomain+"/wp-content/themes/golf/proxy.php?proxy="+entryLinkHref);
	  //entryLink.setAttribute('onclick', "window.open('"+entryLinkHref+"','rsrEvent','width=600,height=300,resizable=yes, scrollbars=yes'); return false;");
	   entryLink.setAttribute('class', 'cbox calTitle');
      entryLink.appendChild(document.createTextNode(title));
      li.appendChild(entryLink);
	  
	  timeSpan.appendChild(document.createTextNode(timeString));
	  
	  dateSpan.appendChild(timeSpan);
	  dateSpan.appendChild(myDateString);
      li.appendChild(dateSpan);
    } else {
		titleSpan.appendChild(document.createTextNode(title));
		dateSpan.appendChild(timeSpan);
	  	dateSpan.appendChild(myDateString);
      	li.appendChild(titleSpan);
		li.appendChild(dateSpan);
    }	    

    /* append the list item onto the unordered list */
    ul.appendChild(li);
	
  }
  
  
  
  eventDiv.appendChild(ul);
  
 /* var fullCalSpan = document.createElement('span');
  var fullCalA = document.createElement('a');

  
  fullCalA.setAttribute('href', 'http://'+myDomain+'/wp-content/themes/golf/fullCal.php');
  fullCalA.setAttribute('class', 'fullCal');
  fullCalA.appendChild(document.createTextNode("Full Calendar"));
  
  fullCalSpan.setAttribute('class', 'fullCalLink');
  fullCalSpan.appendChild(fullCalA);
  
  eventDiv.appendChild(fullCalSpan);*/

	initColorbox();

}// JavaScript Document

function initColorbox(){

	$(".cbox").colorbox({iframe:true, innerWidth:575, innerHeight:200});
	$(".fullCal").colorbox({width:800, height:600});
}
