// Load jQuery
google.load("jquery", "1");
google.setOnLoadCallback(function() {
	$("div.gcal").each(function(){
		var gcal = $(this).attr("gcal");
		if(gcal) {
			calendarListing(this, gcal);
		} else {
			$("<p>No Google Calendar ID was supplied.</p>").appendTo($(this));
		}
	});
	
	$(".rotatingimages").each(function() {
		var rotator = new rotatingImages();
		rotator.init(this);
		$(this).hide();
	});
	
	// form enhancing script
	$("#ipbf-tblStdResponseControl").find("input[type='text']").width("100%").css({'font-size':'1.5em'});
	$(".ipbf-TextInput-SingleLine").width("99%").css({'font-size':'1.5em'});
	$("#ipbf-tblStdResponseControl textarea").width("100%").css({'font-size':'1.5em'});

	// FAQ Links
	if($("div#anchorlinks").length>0) {
		anchorlinks($("#content div.lining"));
	}

});

function anchorlinks(element) {
	$(element).prepend('<a name="top"></a>');
	
	var anchors = "";
	$(element).find("h2").each(function(i) {
		anchors += '<li><a href="#anchor'+i+'">'+$(this).text()+'</a></li>';
		$(this).prepend('<a name="anchor'+i+'"></a>');
	});
	
	$(element).find("hr").each(function() {
		$(this).before('<p style="text-align: right;"><a href="#top">Back to Top</a></p>');
	});
	
	$("div#anchorlinks").html("<ul>"+anchors+"</ul>");
}

// Rotating Images Stuff
function rotatingImages() {
	this.images = new Array();
	this.timeout = 7000;
}
rotatingImages.prototype.init = function(element) {
	this.container = $('<div class="container"></div>');
	var imgs = $(element).find("img");
	if(imgs.length>0) {
		this.container.insertAfter($(element));
		
		for(i=0; i<imgs.length; i++) {
			this.images.push({
				'img' : $(imgs[i]),
				'width' : $(imgs[i]).attr("width")+"px",
				'height' : $(imgs[i]).attr("height")+"px"
			});
		}
		
		this.container.css("overflow","hidden"); // Make sure things don't overflow
		this.container.css("position","relative"); // Set to "relative" so we can position the child display divs
		this.container.html("<div class=\"firstImage\">a</div><div class=\"secondImage\">b</div>"); // Create child display div 1 and 2
		this.display0 = this.container.find(".firstImage");
		this.display0.css({position:"absolute", top:"0", left:"0", width:"100%"}); // Absolute position the childs
		this.display1 = this.container.find(".secondImage");
		this.display1.css({position:"absolute", top:"0", left:"0", width:"100%"});
		this.display1.hide(); // Hide the second child for now
		this.currentItem = -1; // initializing local variable so to keep count correctly.
		this.currentDisplay = 0; // 0 is firstDisplay, 1 is secondDisplay
		this.displayNextItem(); // this function calls itself every 4 seconds. see below
	}
}
rotatingImages.prototype.displayNextItem = function() {
	/*
	Rotation of news items are done by fading and showing 2 child div's alternately, while writing the correct
	content into the div that is about to be shown
	*/
	var nextItem = this.currentItem+1; // Get next item id
	if(nextItem>=this.images.length) { // Rotate back to 0th item
		nextItem = 0;
	}
	
	var thisobj = this;
	
	if(this.currentDisplay>0) { // See which one is the currently hidden display
		this.display1.html(this.images[nextItem].img); // Write to the currently hidden display div
		this.display0.fadeOut("slow", function() { // Hide the "current" display div

		}); 
		thisobj.display1.fadeIn("slow", function() {
			thisobj.container.animate({
				width: thisobj.images[nextItem].width,
				height: thisobj.images[nextItem].height
			});
			
			thisobj.currentDisplay = 0; // Mark the change in hidden vs. displayed status
			thisobj.currentItem = nextItem;
			function bah() {
				thisobj.displayNextItem();
			}
			setTimeout(bah,3000);

		}); // Show the currently hidden div
		
	} else {
		this.display0.html(this.images[nextItem].img);
		this.display1.fadeOut("slow", function() {

		});
		thisobj.display0.fadeIn("slow", function(){
			thisobj.container.animate({
				width: thisobj.images[nextItem].width,
				height: thisobj.images[nextItem].height
			});
	
			thisobj.currentDisplay = 1;
			thisobj.currentItem = nextItem;
			function bah() {
				thisobj.displayNextItem();
			}
			setTimeout(bah,3000);
		});
	}
}

// Calendar Stuff
function calendarListing(element, gcal) {
	var gcaljsonurl = "http://www.google.com/calendar/feeds/"+gcal+"/public/full?alt=json-in-script&orderby=starttime&max-results=4&singleevents=true&sortorder=ascending&futureevents=true&timezone=PST&callback=?";
	
	$.getJSON(gcaljsonurl, function(data) {
		var html = "";
		
		if(!data.feed.entry) {
			var html = '<p>No events currently scheduled.</p>';
		} else {
			$.each(data.feed.entry, function(i,entry) {
				var eventhtml = "";
			
				var title = entry.title.$t;
				var start = entry['gd$when'][0].startTime;
				var dateString = formatGCalTime(start);
				var content = dateString + " " + entry.content.$t;
				
				for (var linki = 0; linki < entry['link'].length; linki++) {
					if (entry['link'][linki]['type'] == 'text/html' &&
						entry['link'][linki]['rel'] == 'alternate') {
						//title = '<a href="'+entry['link'][linki]['href']+'">'+title+'</a>';
						break;
					}
				}

				eventhtml = '<div class="datebox">'+dateString+'</div><div class="eventdetails"><h3>'+title+'</h3> <p>'+content+'</p></div>';
				
				html += '<li class="event">'+eventhtml+'</li>';
				
			});
			
			var html = '<div><ul class="eventlist">'+html+'</ul><p>Powered by Google Calendar.  Download the <a href="http://www.google.com/calendar/ical/'+gcal+'/public/basic.ics">&ldquo;'+data.feed.title.$t+'&rdquo; calendar in iCal format!</a></p></div>';
		}
		
		$(html).appendTo(element).hide().slideDown("slow");
	});
}

function formatGCalTime(gCalTime) { // From http://code.google.com/apis/gdata/samples/cal_sample.html ... except for last little bit.
  // text for regex matches
  var remtxt = gCalTime;

  function consume(retxt) {
    var match = remtxt.match(new RegExp('^' + retxt));
    if (match) {
      remtxt = remtxt.substring(match[0].length);
      return match[0];
    }
    return '';
  }

  // minutes of correction between gCalTime and GMT
  var totalCorrMins = 0;

  var year = consume('\\d{4}');
  consume('-?');
  var month = consume('\\d{2}');
  consume('-?');
  var dateMonth = consume('\\d{2}');
  var timeOrNot = consume('T');

  // if a DATE-TIME was matched in the regex 
  if (timeOrNot == 'T') {
    var hours = consume('\\d{2}');
    consume(':?');
    var mins = consume('\\d{2}');
    consume('(:\\d{2})?(\\.\\d{3})?');
    var zuluOrNot = consume('Z');

    // if time from server is not already in GMT, calculate offset
    if (zuluOrNot != 'Z') {
      var corrPlusMinus = consume('[\\+\\-]');
      if (corrPlusMinus != '') {
        var corrHours = consume('\\d{2}');
        consume(':?');
        var corrMins = consume('\\d{2}');
        totalCorrMins = (corrPlusMinus=='-' ? 1 : -1) * 
            (Number(corrHours) * 60 + 
	    (corrMins=='' ? 0 : Number(corrMins)));
      }
    } 

    // get time since epoch and apply correction, if necessary
    // relies upon Date object to convert the GMT time to the local
    // timezone
    var originalDateEpoch = Date.UTC(year, month - 1, dateMonth, hours, mins);
    var gmtDateEpoch = originalDateEpoch + totalCorrMins * 1000 * 60;
    var ld = new Date(gmtDateEpoch);

    // date is originally in YYYY-MM-DD format
    // time is originally in a 24-hour format
    // this converts it to MM/DD hh:mm (AM|PM) 
    dateString = (ld.getMonth() + 1) + '/' + ld.getDate() + ' ' + 
        ((ld.getHours()>12)?(ld.getHours()-12):(ld.getHours()===0?12:
	ld.getHours())) + ':' + ((ld.getMinutes()<10)?('0' + 
	ld.getMinutes()):(ld.getMinutes())) + ' ' + 
	((ld.getHours()>=12)?'PM':'AM');
	
	var monthsarray = new Array('Jan', 'Feb', 'Mar','Apr', 'May','Jun', 'Jul', 'August', 'Sep','Oct', 'Nov', 'Dec');
	var monthstr = monthsarray[ld.getMonth()];
	
	var datestr = ld.getDate();
	
	dateString = '<span class="month">' + monthstr + '</span> <span class="date">' + datestr + '</span> <span class="hour">' +((ld.getHours()>12)?(ld.getHours()-12):(ld.getHours()===0?12:
	ld.getHours())) + ':' + ((ld.getMinutes()<10)?('0' + 
	ld.getMinutes()):(ld.getMinutes())) + ' ' + 
	((ld.getHours()>=12)?'PM':'AM') + '</span>';
  } else {
    // if only a DATE was matched
	var monthsarray = new Array('Jan', 'Feb', 'Mar','Apr', 'May','Jun', 'Jul', 'August', 'Sep','Oct', 'Nov', 'Dec');
	var monthstr = monthsarray[parseInt(month)-1];
	
	var datestr = dateMonth;
	
	var dateString =  '<span class="month">' + monthstr + '</span> <span class="date">' + datestr + '</span>';
  }
  return dateString;
}