/* !Begin Custom Functions 

2011-03-26   Dylan Valade   Added extraLargeButton to round 5px
2011-09-02   Dylan Valade   Removed Galleria, added Nivo Slider
*/

// Define an empty function for browsers that don't support console.log
if("undefined" === typeof console) {

	console = { log: function() { } };
}

// Define custom function to return posts from a Facebook user
$.facebook = function (options, callback) {

	// Fail if the options arguemnt isn't set
	if (!options) {
		return false;
	}
	
	// Initialize variables
	var	defaultOptions	= {limit: 5, from: null},
		options			= $.extend(true, defaultOptions, options),
		url				= "http://graph.facebook.com/" + options.from + "/feed?limit=" + options.limit + "&callback=?";

	// Call Facebook JSONP
	$.getJSON(url, function (json) { 
	
		// Execute the callback
		callback(json);
	});	
};

// Display a slideshow of content using the ColorBox plugin
function loadSlideshowFromCache(slideshowId, options) {

    // Initialize the options by merging the defaults and those passed
    options =   $.extend(true, {
                    container: "#slideshow_photos",
                    colorboxOptions: {
                        iframe: function() {

                            return $(this).hasClass("external");
                        },
                        innerHeight: function() {

                            return ($(this).hasClass("external")) ? 385 : false;
                        },
                        innerWidth: function() {

                            return ($(this).hasClass("external")) ? 640 : false;
                        },
                        open: true,
                        slideshow: false,
                        slideshowAuto: false,
                        title: function() {
                        
                            var itemUrl = $("body").data("slideshowItemUrls")[$(this).attr("href")];
                        
                            return (undefined != itemUrl) ? '<a href="' +itemUrl + '" target="_blank">' + $(this).attr("title") + '</a>' : $(this).attr("title");
                        }
                    },
                    hideContainer: true,
                    hidePhotos: false
                }, options);

    // Verify an ID is provided
    if ("" != slideshowId) {

        // Construct the slideshow HTML if it doesn't already exist then load
        if (0 == $("a[rel='" + slideshowId + "']").length) {

            // Load the cached data
//          $.getJSON("cache/slideshows/" + slideshowId + ".json", {}, function (slideshow, textStatus) {
            $.getJSON("/cache/" + slideshowId + ".json", {}, function (slideshow, textStatus) {

                if ("success" == textStatus) {

                    // Initialize variables
                    var html                = '',
                        itemClass,
                        itemPath,
                        slideshowItemUrls   = {};

/*
                    $(data).closest("img").each(function () {

                        html += '<a href="' + $(this).attr("src") + '" rel="' + slideshowId + '" title="' + $(this).attr("alt") + '">' + $(this).attr("alt") + '</a> ';
                    });
*/

                    // Generate the HTML required by Colorbox
                    $.each(slideshow.items, function(i, item) {

                        // Open the item inline with Colorbox
                        if ("" != item.path) {

                            itemPath    = item.path;
                            itemClass   = "internal";
                        }

                        // Open the item (e.g. a YouTube video) in an iFrame with ColorBox
                        else {

                            itemPath    = item.url;
                            itemClass   = "external";
                        }

                        // Save the URL for an item if provided
                        if ("" != item.path && "" != item.url) {

                            slideshowItemUrls[item.path] = item.url;
                        }

                        html += '<a href="' + itemPath + '" rel="' + slideshow.id + '" class="' + itemClass + '" title="' + item.caption + '" target="' + item.target + '">' + item.caption + '</a> ';
                    });

                    // Save the item path-to-URL mapping to the DOM
                    $("body").data("slideshowItemUrls", $.extend($("body").data("slideshowItemUrls"), slideshowItemUrls));

                    // Append the HTML to the DOM and optionally hide the container or individual photos
                    if (options.hideContainer)  $(options.container).append(html).hide();
                    else                        $(options.container).append(html);

                    if (options.hidePhotos)
                        $("a[rel='" + slideshowId + "']").hide();

                    // Open Colorbox with the new HTML
                    $("a[rel='" + slideshowId + "']").colorbox(options.colorboxOptions);

                }
                else { }

            }, "html");
        }

        // Open Colorbox from the existing HTML
        else {

            $("a[rel='" + slideshowId + "']").colorbox(options.colorboxOptions);
        }
    }
};


// Display a Nivo slider
function loadNivoSlideshowFromCache(slideshowId, container) {

    // Verify an ID is provided
    if ("" != slideshowId) {

		// Load the cached data
		$.getJSON("/cache/" + slideshowId + ".json", {}, function (slideshow, textStatus) {

			if ("success" == textStatus) {
				
				// Initialize variables
				var html                = '',
					itemClass,
					itemPath,
					slideshowItemUrls   = {};

				// Generate the HTML required by Nivo
				$.each(slideshow.items, function(i, item) {

					// Open the item inline with Colorbox
					if ("" != item.path) {

						itemPath    = item.path;
						itemClass   = "internal";
					}

					// Open the item (e.g. a YouTube video) in an iFrame with ColorBox
					else {

						itemPath    = item.url;
						itemClass   = "external";
					}

					// Save the URL for an item if provided
					if ("" != item.path && "" != item.url) {

						slideshowItemUrls[item.path] = item.url;
					}

					html += '<img src="' + itemPath + '" class="' + itemClass + '" title="' + item.caption + '" target="' + item.target + '" alt="' + item.caption + '" /> ';
					
					// TODO: Add HTML captions to DOM here...
					
				});

				// Save the item path-to-URL mapping to the DOM
				// $("body").data("slideshowItemUrls", $.extend($("body").data("slideshowItemUrls"), slideshowItemUrls));

				// Append the HTML to the DOM and optionally hide the container or individual photos
				$(container).append(html);

				// Launch Nivo
				$(container).nivoSlider({
					effect: 'fade',
					controlNav: false,
					captionOpacity: 0,
					pauseTime: 6000,
					directionNav: false
				});
			}
			else { }

		}, "html");
    }
};

/* End Custom Functions */

/* !Begin Event Handlers */
/* End Event Handlers */

/* !Begin Initialization */

// Replace text with custom font using Cufon
/*
Cufon
.replace(".leftMenu a", {hover: {color: "#0082D7"}})
.replace(".headingOneLine, .heading, .label, .leftMenu, .extraLargeButton, .givingLogo");
*/

Cufon.now();


/* End Initialization */

$(document).ready(function(){

	// Retrieve Blog posts
	$('#news').rssfeed('http://blog.ymcarockies.org/?feed=rss', {
		limit: 3, header:false, date:false
	});

	// Initialize accordion
	if (0 != $(".accordion").length)
		$(".accordion").accordion({header: "h2"});


// Apply rounded corners to elements
$(".round5, .linkBar li a, .largeButton, .extraLargeButton").corner("5px");
$(".logo a").corner("bottom 5px");
$(".roundTop").corner("top 5px");

 // rotating Banners
	$("#rotatingBanners ul").cycle({
		fx: 'fade', // choose your transition type, ex: fade, scrollUp, shuffle, etc...
		random: 1,	// randomly select a starting slide
		pause: 1	// pause slideshow when mouse is hovering
	});

	// Return latest tweet and post on Twitter and Facebook
	$.twitter({from: 'ymcarockies', limit: 1, replies: false, retweets: true}, function (tweets) {
	
		$("li.twitter").html("<span class='tweet'>" + tweets["results"][0]["text"] + "</span><br /><a href='http://www.twitter.com/ymcarockies/status/" + tweets["results"][0]["id"] + "' target='_blank'>View on Twitter</a>");
	});

/*
	$.facebook({from: "45678993671", limit: 10}, function (json) {

		$("li.facebook").html("<span class='post'>" + json["data"][0]["message"] + "</span><br /><a href='http://www.facebook.com/home.php?ref=home#!/pages/Estes-Park-CO-Winter-Park-CO/YMCA-of-the-Rockies/45678993671' target='_blank'>View on Facebook</a>");
	});
*/

    // Load photo slideshow on click
    $(".imageContainer.relative a").click(function (e) {

        // Prevent the link from being followed
        e.preventDefault();

        // Load the slideshow
        loadSlideshowFromCache($(this).attr("id"), {container: "body", hideContainer: false, hidePhotos: true});
    });


});

