var slideInterval = setInterval('slideReady()',100);

$(document).ready(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));
		}
	});

	// FAQ Links
	if($("div#anchorlinks").length>0) {
		anchorlinks($("#content div.lining"));
	}
	
	$('#frontslide').cycle({
		'height': 250
	});

});

function slideReady() {
	if($('.una_slide').length<=0 || $('.una_slide').height()>0) {
		clearInterval(slideInterval);
		
		$('.una_slides').each(function() {
			var height = 0;
			$(this).find('.una_slide').each(function() {
				var newh = $(this).height();
				if(newh > height) {
					height = newh;	
				}
			});
			
			if($("#home, #eventspage").length > 0) {				
				$('.una_slide .attachment-spotlight-thumbnail').each(function() {
					var thumbnail_width = $(this).width();
					var thumbnail_height = $(this).height();
					
					if(thumbnail_width < 525 || thumbnail_height < 250) {
						$(this).css({"margin": "17px 17px 0 0"});
					}
				});
				
				$(this).after('<div id="cycle_nav">').cycle({
					'height': height,
					'pager': '#cycle_nav'
				});
			} else {
				$(this).cycle({
					'height': height
				});
			}
		});
	}
}

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>");
}

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

function MM_findObj(n, d) { // v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function YY_checkform() { // v4.71
//copyright (c)1998,2002 Yaromat.com
  var a=YY_checkform.arguments,oo=true,v='',s='',err=false,r,o,at,o1,t,i,j,ma,rx,cd,cm,cy,dte,at;
  for (i=1; i<a.length;i=i+4){
    if (a[i+1].charAt(0)=='#'){r=true; a[i+1]=a[i+1].substring(1);}else{r=false}
    o=MM_findObj(a[i].replace(/\[\d+\]/ig,""));
    o1=MM_findObj(a[i+1].replace(/\[\d+\]/ig,""));
    v=o.value;t=a[i+2];
    if (o.type=='text'||o.type=='password'||o.type=='hidden'){
      if (r&&v.length==0){err=true}
      if (v.length>0)
      if (t==1){ //fromto
        ma=a[i+1].split('_');if(isNaN(v)||v<ma[0]/1||v > ma[1]/1){err=true}
      } else if (t==2){
        rx=new RegExp("^[\\w\.=-]+@[\\w\\.-]+\\.[a-zA-Z]{2,4}$");if(!rx.test(v))err=true;
      } else if (t==3){ // date
        ma=a[i+1].split("#");at=v.match(ma[0]);
        if(at){
          cd=(at[ma[1]])?at[ma[1]]:1;cm=at[ma[2]]-1;cy=at[ma[3]];
          dte=new Date(cy,cm,cd);
          if(dte.getFullYear()!=cy||dte.getDate()!=cd||dte.getMonth()!=cm){err=true};
        }else{err=true}
      } else if (t==4){ // time
        ma=a[i+1].split("#");at=v.match(ma[0]);if(!at){err=true}
      } else if (t==5){ // check this 2
            if(o1.length)o1=o1[a[i+1].replace(/(.*\[)|(\].*)/ig,"")];
            if(!o1.checked){err=true}
      } else if (t==6){ // the same
            if(v!=MM_findObj(a[i+1]).value){err=true}
      }
    } else
    if (!o.type&&o.length>0&&o[0].type=='radio'){
          at = a[i].match(/(.*)\[(\d+)\].*/i);
          o2=(o.length>1)?o[at[2]]:o;
      if (t==1&&o2&&o2.checked&&o1&&o1.value.length/1==0){err=true}
      if (t==2){
        oo=false;
        for(j=0;j<o.length;j++){oo=oo||o[j].checked}
        if(!oo){s+='* '+a[i+3]+'\n'}
      }
    } else if (o.type=='checkbox'){
      if((t==1&&o.checked==false)||(t==2&&o.checked&&o1&&o1.value.length/1==0)){err=true}
    } else if (o.type=='select-one'||o.type=='select-multiple'){
      if(t==1&&o.selectedIndex/1==0){err=true}
    }else if (o.type=='textarea'){
      if(v.length<a[i+1]){err=true}
    }
    if (err){s+='* '+a[i+3]+'\n'; err=false}
  }
  if (s!=''){alert('Whoops! The required information is incomplete or contains errors:\t\t\t\t\t\n\n'+s)}
  document.MM_returnValue = (s=='');
}

