google.load("gdata", "1.x", { packages : ["calendar"] });

$(document).ready(function(){
	//fancybox
	$(".fancybox").fancybox();
	$("#content .aside .word_of_the_day .listen a").fancybox({
		'width':200,
		'height':20,
		'type':'iframe'
	});
	// accordion
	$('.main .accordion').accordion({ animated: 'bounceslide', autoHeight: false, collapsible: true, active: -1 });
	
	// inserting non-essential divs
	$('#content .aside .slide_details, #content .aside .nav').append('<div class="top"></div><div class="bottom"></div>');
	
	// slideshows
	$('.home .main .slideshow').cycle({ 
		fx: 'scrollDown',
		timeout: 10000, 
		pager: '.slideshow_nav',
		after: function(currSlideElement, nextSlideElement, options, forwardFlag){
		    showText(options.currSlide);
		}
	});
	$('.slide_details .slide:not(:first-child)').hide();
	function showText(index){
		$('.slide_details .slide').hide();
		$('.slide_details .slide:eq('+ index +')').fadeIn();
	}
	
	$('.aside .slideshow .slides').cycle({ 
		fx: 'fade',
		timeout: 10000, 
		pager: '.slideshow_nav'
	});
	
	/* Block for Vimeo videos on Videos Page */
	var albums = [];
	var toLoad = 0;
	if( $(".page-Videos").size() > 0)
	{
		//get user info for albums list
		$.getJSON('http://vimeo.com/api/v2/user4116663/albums.json?callback=?', function(data)
		{
			albums = data;
			for(var i=0;i<albums.length;i++)
			{
				if( albums[i].title == "History")
				{
					var temp = albums[i];
					albums[i] = albums[i-1];
					albums[i-1] = temp;
				}
				$('.page-Videos .main .slides').append('<div class="slide"><ul></ul></div>');
			}
			toLoad = albums.length;
			$.each(albums, function(i,album)
			{
				loadAlbum(i);
			});
		});
	}
	
	function loadAlbum(index)
	{
		if( index > albums.length)
			return;
		var album = albums[index];
		$.getJSON('http://vimeo.com/api/v2/album/'+album.id+'/videos.json?callback=?', function(data)
		{
			var block = '';
			$.each(data, function(i, video)
			{
				if( (i+1) % 3 == 0 )
					block += '<li class="last">';
				else if( i%3 == 0)
					block += '<li class="first">';
				else
					block += "<li>";
				block += "<a href=\"http://vimeo.com/"+ video.id +"\" rel=\""+  video.id +"\"><img src=\""+ video.thumbnail_medium +"\" />"+ video.title +"</a></li>";
			});
			$('.page-Videos .main .slides .slide:eq('+index+') ul').append( block );
			//console.log(block);
			toLoad--;
			if( toLoad == 0)
			{
				$('.page-Videos .main .slideshow .slides .slide a').each( function() {
					$(this).bind( "click", function() {
						$('.page-Videos .main .slideshow .slides .slide a').attr("class","");
						$(this).attr("class","active");
						$("#current_video").empty().append('<object width="655" height="368"><param name="allowfullscreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="movie" value="http://vimeo.com/moogaloop.swf?clip_id='+ $(this).attr("rel") +'&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=1&amp;show_portrait=1&amp;color=00ADEF&amp;fullscreen=1&amp;autoplay=0&amp;loop=0" /><embed src="http://vimeo.com/moogaloop.swf?clip_id='+ $(this).attr("rel") +'&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=1&amp;show_portrait=1&amp;color=00ADEF&amp;fullscreen=1&amp;autoplay=0&amp;loop=0" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="655" height="368"></embed></object>');
						return false;
					});
				});
				if( $(".page-Videos .main .slideshow .slides .slide:first").size() > 0 )
				{
					$(".page-Videos .main .slideshow .slides .slide a:first").click();
				}
				$('.page-Videos .main .slideshow .slides').cycle({
					fx: 'fade',
					timeout: 0,
					pager: '.slideshow_nav',
					containerResize: 0,
					before: function(curr, next, opts, fwd) {
					  var $ht = $(this).height();
					  $(this).parent().animate({height: $ht});
					}
				});
				$('.page-Videos .main .slideshow_nav a').each( function(i,link) {
					$(link).text(albums[i].title);
				});
			}
		});
	}
	/* End Vimeo Block */
	
	// home page youtube
	$.getJSON('http://gdata.youtube.com/feeds/api/users/ChoctawNationVideo/uploads?alt=json-in-script&max-results=1&callback=?', function(data){
		var feed = data.feed;
		var entries = feed.entry || [];
		$.each(entries, function(i,entry){
			var yturl = entry.id.$t;
			var ytid = yturl.substr((yturl.lastIndexOf('/'))+1);
			$('.video .player').empty().append('<object width="300" height="245"><param name="movie" value="http://www.youtube.com/v/'+ytid+'&hl=en&fs=1&rel=0"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/'+ytid+'&hl=en&fs=1&rel=0" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="300" height="245"></embed></object>');
			$('.video .title strong').empty().append(entry.title.$t);
			if(i == 1){
				return false;
			}
		});
	});
	
	function getCalendars(feedUri, whichEvents) {
		var calendarService = new google.gdata.calendar.CalendarService('com.appspot.interactivesampler');
		var feedUri = feedUri;
		var query = new google.gdata.calendar.CalendarEventQuery(feedUri);
		var theDate = new Date();
		var currentDay = theDate.getDate();
		var thisMonth = (theDate.getMonth()) + 1;
		if(thisMonth < 10){
			thisMonth = '0' + thisMonth;
		}else{
			thisMonth = thisMonth.toString();
		}
		var thisYear = theDate.getFullYear();
		var howManyDays = 32 - new Date(thisYear, theDate.getMonth(), 32).getDate();

		var monthName = new Array(12);
		monthName[0]="January";
		monthName[1]="February";
		monthName[2]="March";
		monthName[3]="April";
		monthName[4]="May";
		monthName[5]="June";
		monthName[6]="July";
		monthName[7]="August";
		monthName[8]="September";
		monthName[9]="October";
		monthName[10]="November";
		monthName[11]="December";
		
		$('.calendar .month a').text(monthName[theDate.getMonth()]);
		for(var i=1; i < howManyDays+1; i++){
			if(i < 10){
				i = '0' + i;
			}else{
				i = i.toString();
			}
			$('.calendar ul').append('<li><a href="#">'+ i +'</a></li>');
		};
		
		var startMin = google.gdata.DateTime.fromIso8601(thisYear+'-'+ thisMonth +'-01T00:00:00.000-00:00');
		var startMax = google.gdata.DateTime.fromIso8601(thisYear+'-'+ thisMonth +'-'+ howManyDays +'T00:00:00.000-23:59');
		query.setMinimumStartTime(startMin);
		query.setMaximumStartTime(startMax);
		var callback = function(root) {
			$('body').append('<div id="modal"></div>');
			$('#modal').dialog({
				autoOpen: false,
				modal: true,
				width: 600,
				height: 250
			});
			var eventEntries = root.feed.getEntries();
			var fromDate = google.gdata.DateTime.toIso8601(startMin);
			var toDate = google.gdata.DateTime.toIso8601(startMax);
			$.each(eventEntries, function(i){
				var title = this.getTitle().getText();
				var content = this.getContent().getText();
				var where = this.gd$where[0].valueString;
				var link = this.getLink("alternate", "text/html").getHref();
				var eventTimes = this.getTimes();
				$.each(eventTimes, function(j){
					var dateStart = this.getStartTime().getDate();
					var dateParts = String(dateStart).split(' ');
					var date = dateParts[2];
					if($.browser.msie){
						if(date < 10){
							date = '0'+date;
						}
					}
					$('.calendar a:contains("'+currentDay+'")').css({'color': '#fff', 'text-shadow': '1px 1px 2px rgba(0,0,0,0.25)'});
					$('.calendar a:contains("'+date+'")').append('<div>'+ title +'</div>').addClass('event').attr('href', link).click(function(){
						$('#modal').empty().append("<h4>" + title + "</h4><p>" + content + "</p><p class='meta'>" + dateStart.toString() + "<br />" + where + "<br /><a href='" + link + "'>View event on Google Calendar</a></p>")
						$('#modal').dialog({
							open: function(){
								$('object, embed').hide();
							},
							close: function(){
								$('object, embed').show();
							}
						});
						$('#modal').dialog('open');
						return false;
					});;
				});
			});

		};
		var handleError = function(error) {
			//alert(error);
		};
		calendarService.getEventsFeed(query, callback, handleError);
	}

	getCalendars('http://www.google.com/calendar/feeds/choctawnation.com%40gmail.com/public/full', 'hd_events');
	
	// custom scroller on homepage
	var newsHeight = $('.news .scroll ul').height();
	$('.news .bar').slider({
		orientation: 'vertical',
		animate: true,
		step: 1,
		min: 0,
		max: newsHeight-258,
		value: newsHeight-258,
		slide: function(event, ui){
			$('.news .scroll ul').css('top', ui.value-(newsHeight-258) +'px');
		}
	});
	
	// set input values and clear on focus
	$('#masthead input[type="text"], .application input[type="text"], .contact input[type="text"]').each(function(){
		var which_input = $(this).attr('id');
		var orig_inputval = $('label[for="'+which_input+'"]').text();
		$(this).val(orig_inputval);

		$(this).focus(function(){
			inputval = $(this).val();
			if(inputval == orig_inputval){
				$(this).val('');
			}
		});
		$(this).blur(function(){
			if($(this).val() == ''){
				$(this).val(orig_inputval);
			}
		});
	});
	
	// add icon to pdf links
	$('a[href$=".pdf"]').addClass('pdf').append(' <img src="/images/icon-acrobat.gif" alt="Download PDF File" class="icon" />');
	
	// ie6 selector support
	if($.browser.msie && $.browser.version == '6.0'){
		$('input[type="submit"]').addClass('submit');
		$('input[type="text"], input[type="password"]').addClass('text');
		$('*:first-child').addClass('first-child');
		$('.main>li, .current>a, .related>div, .app_links>div').addClass('child');
	}
	
	// dialog.show() bug in release 1.8 that causes the web page in IE7 only to "jump", in particular
    // it scrolls to the bottom of the page where its apparently appended the markup to the DOM.
    // monkey patch:
    if($.browser.msie){
        var oldDialogOpen = $.ui.dialog.prototype.open;
        $.ui.dialog.prototype.open = function() {
            var originalScrollTop = $(window).scrollTop(),
            result = oldDialogOpen.apply(this, arguments);
            $(window).scrollTop(originalScrollTop);
        };
    }
		$("form#mailer").validate();
});

