$(document).ready(function(){

	jQuery.fn.exists = function(){return jQuery(this).length>0;}
	
	$("a.top").click(function(e){
		e.preventDefault();
		$("html, body").animate({scrollTop: 0}, 250);
	});
	
	/* winners animation */
	$(".winner-link").hover(function(){
		$(this).stop().animate({ top: '-10px', paddingBottom: '15px' }, 125).find("h3").stop().animate({ opacity: 1 }, 125);
	}, function(){
		$(this).stop().animate({ top: '0px', paddingBottom: '5px' }, 125).find("h3").stop().animate({ opacity: 0 }, 125);
	});
	
	$(".mini-box img").each(function(){
		title = $(this).attr("alt");
		if ($("h1").text() == title) { $(this).parent().addClass("active"); }
	});
	$(".mini-box a").hover(function(){
		alt = $("img", this).attr("alt");
		$(this).after('<h4><span>'+alt+'</span></h4>');
		$(".mini-box h4").css("opacity",0).stop(true, true).animate({
			opacity: 1
		}, 150);
	}, function(){
		$(".mini-box h4").stop(true, true).remove();
	});
	
	/* Select text on focus */
	$(".share-page textarea, .v-page textarea").focus(function(){
		$(this).select();
	});
	$(".share-page textarea, .v-page textarea").mouseup(function(e){ e.preventDefault(); });
	
	/* Fix the Youtube z-index bug */
	$("iframe").each(function(){
		var url = $(this).attr("src");
		$(this).attr("src",url+"?wmode=transparent");
	});	
	
	function getYOffset() {
		var pageY;
		if(typeof(window.pageYOffset)=='number') {
			 pageY=window.pageYOffset;
		}
		else {
			 pageY=document.documentElement.scrollTop;
		}
		return pageY;
	}
	
	/* Non-Isotope */
	
	var $list = $(".contestant-boxes");
	
	$(".name-search").focus(function(){
		var val = $(this).val().toLowerCase();
		if (!val) {
			$(".options p > a").text("Remove name filter");
			$(".omit-me").removeClass("omit-me");
		}
		$(".song-active").removeClass("song-active active");
		$("#state-filter option:selected").removeAttr("selected");
	})
	
	$(".name-search").bind("keyup change", function(){
		var val = $(this).val().toLowerCase();
		$(".omit-me").removeClass("omit-me");
		if (val) {
			$(".options p").show().find("a").text("Remove name filter");
			$(".charity-active").removeClass("charity-active active");
			$(".song-active").removeClass("song-active active");
			$("#state-filter option:selected").removeAttr("selected");
			$(".contestant-box").filter(function(){
				return $(this).find("h2 > span").text().toLowerCase().indexOf(val) === -1;
			}).addClass("omit-me");
		} else {
			$(".options p").hide();
			$(".omit-me").removeClass("omit-me");
		}
		$("html, body").animate({scrollTop: 0}, 0);
	});
	
	$("#state-filter").change(function(){
		var val = $("option:selected", this).val();
		if (val) {
			$(".options p").show().find("a").text("Remove state filter");
			
			$(".song-active").removeClass("song-active active");
			$(".name-search").val('');
			
			$(".omit-me").removeClass("omit-me");
			$(".contestant-box").filter(function(){
				return $(this).find("span.state").text() !== val;
			}).addClass("omit-me");
			$("html, body").animate({scrollTop: 0}, 0);
			
		}
	});
	
	$(".song-options a").hover(function(){
		alt = $("img", this).attr("alt");
		$(this).after('<h4><span>'+alt+'</span></h4>');
		$(".song-options h4").css("opacity",0).stop(true, true).animate({
			opacity: 1
		}, 150);
	}, function(){
		$(".song-options h4").stop(true, true).remove();
	});
	
	$(".song-options a").click(function(e){
	
		$(".song-active").removeClass("song-active active");
		$(this).parent().addClass("song-active active");
		var $class = $(this).attr("class");
		
		$(".name-search").val('');
		$("#state-filter option:selected").removeAttr("selected");
		
		$(".omit-me").removeClass("omit-me");
		$(".contestant-box").filter(function(){
			return $(this).find("span.song").attr("class") !== 'song '+$class;
		}).addClass("omit-me");
		$("html, body").animate({scrollTop: 0}, 0);
	
		$(".options p").show().find("a").text("Remove song filter");
		
		e.preventDefault();
	
	});
	
	$(".sort-options a").click(function(e){
	
		e.preventDefault();
		
		$this = $(this);
	
		var width = $this.width();
		$this.addClass("thinking").width(width).animate({ top: 0 }, 250, function(){
		
			$(".sort-active").removeClass("sort-active active");
			$this.parent().addClass("sort-active active");
			$this.removeClass("thinking");
			
			var $class = $this.attr("class");
			if ($class == "alpha-az") {
				$(".options h5").hide();
				$('.contestant-box').sortElements(function(a, b){
					return $("span.org-name", a).text().toLowerCase() > $("span.org-name", b).text().toLowerCase() ? 1 : -1;
				});
			} else if ($class == "alpha-za") {
				$(".options h5").hide();
				$('.contestant-box').sortElements(function(a, b){
					return $("span.org-name", a).text().toLowerCase() < $("span.org-name", b).text().toLowerCase() ? 1 : -1;
				});
			} else if ($class == "votes") {
				$(".options h5").show();
				$('.contestant-box').sortElements(function(a, b){
					return parseInt($("h4", a).text()) < parseInt($("h4", b).text()) ? 1 : -1;
					//return $("h4", a).attr("title") < $("h4", b).attr("title") ? 1 : -1;
				});
			} else if ($class == "city") {
				$(".options h5").hide();
				$('.contestant-box').sortElements(function(a, b){
					return $("span.city", a).text() > $("span.city", b).text() ? 1 : -1;
				});
			} else if ($class == "state") {
				$(".options h5").hide();
				$('.contestant-box').sortElements(function(a, b){
					return $("span.state", a).text() > $("span.state", b).text() ? 1 : -1;
				});
			} else if ($class == "random") {
				$(".options h5").hide();
				$(".contestant-box").sortElements(function(a,b){
					rand = parseInt(Math.random()*100);
					x = rand % 2;
					y = rand > 50 ? 1 : -1;
					return(x * y)
				});
			}
			
			$("html, body").animate({scrollTop: 0}, 0);
			
		});
	
	});
	
	$(".options p a").click(function(e){
		e.preventDefault();
		$(".name-search").val('');
		$(".charity-dropdown").val("*");
		$(".song-active").removeClass("song-active active");
		$("#state-filter option:selected").removeAttr("selected");
		$(".omit-me").removeClass("omit-me");
		$(this).parent().hide();
		$("html, body").animate({scrollTop: 0}, 0);
	});
	
	// make sure they can't submit the form
	$("#search-form").submit(function(){
		return false;
	});
	
	/* Scrolling trick */
	if ($("#options").exists() || $("#submit-story").exists() || $("#share-options").exists()) {
	
		options_offset = $("#options").offset();
		options_height = $("#options").height();
		boxes_height = $(".contestant-boxes").height();
		share_offset = $("#share-options").offset();
		stories_offset = $("#submit-story").offset();
		stories_height = $("#submit-story").height();
		
		gutter = 20;
	
		$(window).scroll(function(){
			
			donate_offset = $("#donate .container").offset();
			share_height = $("#share-options").height();
			scroller = parseInt(window.pageYOffset);
			
			if ($("body").hasClass("stories-page")) {
			
				if (scroller >= (stories_offset.top - gutter)) {
					$("#submit-story").addClass("fixed-on").removeClass("bottom-on");
					if (scroller > (donate_offset.top - stories_height)) {
						$("#submit-story").removeClass("fixed-on").addClass("bottom-on");
					}
				} else {
					$("#submit-story").removeClass("fixed-on").removeClass("bottom-on");
				}
				
			} else if ($("body").hasClass("v-page")) {
				
				if (scroller >= (share_offset.top - gutter)) {
					$("#share-options, .contestant-video").addClass("fixed-on").removeClass("bottom-on");
					if (scroller > (donate_offset.top - share_height)) {
						$("#share-options, .contestant-video").removeClass("fixed-on").addClass("bottom-on");
					}
				} else {
					$("#share-options, .contestant-video").removeClass("fixed-on").removeClass("bottom-on");
				}
				
			} else {
				
				if (options_height < boxes_height) {
			
					if (scroller >= (options_offset.top - gutter)) {
						$("#options, .contestant-boxes").addClass("fixed-on").removeClass("bottom-on");
						if (scroller > (donate_offset.top - options_height)) {
							$("#options, .contestant-boxes").removeClass("fixed-on").addClass("bottom-on");
						}
					} else {
						$("#options, .contestant-boxes").removeClass("fixed-on").removeClass("bottom-on");
					}
				
				}
			
			}
			
		});
		
	}
	
	/* Form validation */
	
	var $email_regex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+[a-zA-Z]+\.[a-zA-Z]{2,4}$/;
	var $phone_regex = /^\d{3}-\d{3}-\d{4}$/;
	var $zip_regex = /^\d{5}$|^\d{5}-\d{4}$|^[ABCEGHJKLMNPRSTVXY]{1}\d{1}[A-Z]{1} \d{1}[A-Z]{1}\d{1}$/;
	
	$("form").submit(function(e){
		var $errors = '';
		$(".form-item").each(function(){
			var $this = $(this);
			if ($this.hasClass("select")) {
				var $input = $("select", this);
				var $label = $("label", this);
				if ($input.val() == '') {
					$label.addClass("mistake");
					$errors += '<li><strong>'+$label.html()+'</strong> needs a value.</li>';
				}
			} else if ($this.hasClass("textarea")) {
				var $input = $("textarea", this);
				var $label = $("label", this);
				if ($input.val() == '') {
					$label.addClass("mistake");
					$errors += '<li><strong>'+$label.html()+'</strong> needs a value.</li>';
				}
			} else if ($this.hasClass("checkbox")) {
				var $input = $("input", this);
				var $label = $("label", this);
				if (!$input.is(":checked")) {
					$label.addClass("mistake");
					if ($input.hasClass("citizen")) {
						$errors += '<li>Please agree to being a <strong>citizen of the US or Canada</strong>.</li>';
					} else {
						$errors += '<li>Please agree to the <strong>rules agreement</strong>.</li>';
					}
				}
			} else {
				var $input = $("input", this);
				var $label = $("label", this);
				$label.removeClass("mistake");
				if ($input.hasClass("text")) {
					if ($input.val() == '') {
						$label.addClass("mistake");
						$errors += '<li><strong>'+$label.html()+'</strong> needs a value.</li>';
					}
				} else if ($input.hasClass("email")) {
					if ($input.val() == '') {
						$label.addClass("mistake");
						$errors += '<li><strong>'+$label.html()+'</strong> needs a value.</li>';
					} else if (!$email_regex.test($input.val())) {
						$label.addClass("mistake");
						$errors += '<li>The value entered for <strong>'+$label.html()+'</strong> is invalid.</li>';
					}
				} else if ($input.hasClass("phone")) {
					if ($input.val() == '') {
						$label.addClass("mistake");
						$errors += '<li><strong>'+$label.html()+'</strong> needs a value.</li>';
					} else if (!$phone_regex.test($input.val())) {
						$label.addClass("mistake");
						$errors += '<li>The value entered for <strong>'+$label.html()+'</strong> is invalid.</li>';
					}
				} else if ($input.hasClass("zip")) {
					if ($input.val() == '') {
						$label.addClass("mistake");
						$errors += '<li><strong>'+$label.html()+'</strong> needs a value.</li>';
					} else if (!$zip_regex.test($input.val().toUpperCase())) {
						$label.addClass("mistake");
						$errors += '<li>The value entered for <strong>'+$label.html()+'</strong> is invalid.</li>';
					}
				} else if ($input.hasClass("checking")) {
					if ($input.val() != 10) {
						$label.addClass("mistake");
						$errors += '<li>Please answer the <strong>math problem</strong> correctly.</li>';
					}
				}
			}
		});
		if ($errors != '') {
			$("#message-box").empty().show().prepend('<div class="banner"><div class="radial"><div class="stitching" id="errors"></div></div></div>').css("margin-bottom","2em");
			$("#errors").append('<h3>I&rsquo;m sorry, but your form couldn&rsquo;t be submitted. Please enter the following values:</h3><ul>'+$errors+'</ul>');
			e.preventDefault();
			if ($("body").hasClass("stories-page")) {
				$("#errors").append('<p><a href="#">This box is in the way! Make it go away.</a></p>');
				$("#errors a").click(function(f){
					f.preventDefault();
					$("#message-box").fadeOut(250);
				});
			}
			$("html, body").animate({scrollTop: 0}, 250);
		} else {
			$("#message-box").empty();
			$(":submit").attr("disabled","disabled").val("Submitting...");
			return true;
		}
	});
	
	$.ajax({
		url: 'http://api.twitter.com/1/statuses/user_timeline.json?screen_name=pinkglovedance&trim_user=1&count=3&include_rts=1&callback=?',
		dataType: 'json',
		success: displayTwitterFeed
	});
	
	function displayTwitterFeed(result) {
		var outputTemplate = "<p>{0} <small><a href=\"{1}\">{2}</a></small></p>";
		$.each(result, function (i, item) {
			var tweet = item.text.parseURL().parseUsername().parseHashtag();
			var createdAt = $.browser.msie ? item.created_at : $.timeago(dateFormat(item.created_at, "isoUtcDateTime"));
			var source = item.source;
			var tweetURL = "http://twitter.com/pinkglovedance/status/" + item.id_str;
			$(".twitter").append(outputTemplate.format(tweet, tweetURL, createdAt));
		});
	}
	
	String.prototype.parseURL = function () {
		return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/g, function (url) {
			return url.link(url);
		});
	};
	String.prototype.parseUsername = function () {
		return this.replace(/[@]+[A-Za-z0-9-_]+/g, function (u) {
			var username = u.replace("@", "")
			return u.link("http://twitter.com/" + username);
		});
	};
	String.prototype.parseHashtag = function () {
		return this.replace(/[#]+[A-Za-z0-9-_]+/g, function (t) {
			var tag = t.replace("#", "%23")
			return t.link("http://search.twitter.com/search?q=" + tag);
		});
	};
	String.prototype.format = function () {
		var s = this,
					i = arguments.length;
		while (i--) {
			s = s.replace(new RegExp('\\{' + i + '\\}', 'gm'), arguments[i]);
		}
		return s;
	};

});

function addCommas(nStr) {
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

jQuery.fn.sortElements = (function(){
 
    var sort = [].sort;
 
    return function(comparator, getSortable) {
 
        getSortable = getSortable || function(){return this;};
 
        var placements = this.map(function(){
 
            var sortElement = getSortable.call(this),
                parentNode = sortElement.parentNode,
 
                // Since the element itself will change position, we have
                // to have some way of storing its original position in
                // the DOM. The easiest way is to have a 'flag' node:
                nextSibling = parentNode.insertBefore(
                    document.createTextNode(''),
                    sortElement.nextSibling
                );
 
            return function() {
 
                if (parentNode === this) {
                    throw new Error(
                        "You can't sort elements if any one is a descendant of another."
                    );
                }
 
                // Insert before flag:
                parentNode.insertBefore(this, nextSibling);
                // Remove flag:
                parentNode.removeChild(nextSibling);
 
            };
 
        });
 
        return sort.call(this, comparator).each(function(i){
            placements[i].call(getSortable.call(this));
        });
 
    };
 
})();

/*
 * timeago: a jQuery plugin, version: 0.9.3 (2011-01-21)
 * @requires jQuery v1.2.3 or later
 *
 * Timeago is a jQuery plugin that makes it easy to support automatically
 * updating fuzzy timestamps (e.g. "4 minutes ago" or "about 1 day ago").
 *
 * For usage and examples, visit:
 * http://timeago.yarp.com/
 *
 * Licensed under the MIT:
 * http://www.opensource.org/licenses/mit-license.php
 *
 * Copyright (c) 2008-2011, Ryan McGeary (ryanonjavascript -[at]- mcgeary [*dot*] org)
 */
(function($) {
  $.timeago = function(timestamp) {
    if (timestamp instanceof Date) {
      return inWords(timestamp);
    } else if (typeof timestamp === "string") {
      return inWords($.timeago.parse(timestamp));
    } else {
      return inWords($.timeago.datetime(timestamp));
    }
  };
  var $t = $.timeago;

  $.extend($.timeago, {
    settings: {
      refreshMillis: 60000,
      allowFuture: false,
      strings: {
        prefixAgo: null,
        prefixFromNow: null,
        suffixAgo: "ago",
        suffixFromNow: "from now",
        seconds: "less than a minute",
        minute: "about a minute",
        minutes: "%d minutes",
        hour: "about an hour",
        hours: "about %d hours",
        day: "a day",
        days: "%d days",
        month: "about a month",
        months: "%d months",
        year: "about a year",
        years: "%d years",
        numbers: []
      }
    },
    inWords: function(distanceMillis) {
      var $l = this.settings.strings;
      var prefix = $l.prefixAgo;
      var suffix = $l.suffixAgo;
      if (this.settings.allowFuture) {
        if (distanceMillis < 0) {
          prefix = $l.prefixFromNow;
          suffix = $l.suffixFromNow;
        }
        distanceMillis = Math.abs(distanceMillis);
      }

      var seconds = distanceMillis / 1000;
      var minutes = seconds / 60;
      var hours = minutes / 60;
      var days = hours / 24;
      var years = days / 365;

      function substitute(stringOrFunction, number) {
        var string = $.isFunction(stringOrFunction) ? stringOrFunction(number, distanceMillis) : stringOrFunction;
        var value = ($l.numbers && $l.numbers[number]) || number;
        return string.replace(/%d/i, value);
      }

      var words = seconds < 45 && substitute($l.seconds, Math.round(seconds)) ||
        seconds < 90 && substitute($l.minute, 1) ||
        minutes < 45 && substitute($l.minutes, Math.round(minutes)) ||
        minutes < 90 && substitute($l.hour, 1) ||
        hours < 24 && substitute($l.hours, Math.round(hours)) ||
        hours < 48 && substitute($l.day, 1) ||
        days < 30 && substitute($l.days, Math.floor(days)) ||
        days < 60 && substitute($l.month, 1) ||
        days < 365 && substitute($l.months, Math.floor(days / 30)) ||
        years < 2 && substitute($l.year, 1) ||
        substitute($l.years, Math.floor(years));

      return $.trim([prefix, words, suffix].join(" "));
    },
    parse: function(iso8601) {
      var s = $.trim(iso8601);
      s = s.replace(/\.\d\d\d+/,""); // remove milliseconds
      s = s.replace(/-/,"/").replace(/-/,"/");
      s = s.replace(/T/," ").replace(/Z/," UTC");
      s = s.replace(/([\+\-]\d\d)\:?(\d\d)/," $1$2"); // -04:00 -> -0400
      return new Date(s);
    },
    datetime: function(elem) {
      // jQuery's `is()` doesn't play well with HTML5 in IE
      var isTime = $(elem).get(0).tagName.toLowerCase() === "time"; // $(elem).is("time");
      var iso8601 = isTime ? $(elem).attr("datetime") : $(elem).attr("title");
      return $t.parse(iso8601);
    }
  });

  $.fn.timeago = function() {
    var self = this;
    self.each(refresh);

    var $s = $t.settings;
    if ($s.refreshMillis > 0) {
      setInterval(function() { self.each(refresh); }, $s.refreshMillis);
    }
    return self;
  };

  function refresh() {
    var data = prepareData(this);
    if (!isNaN(data.datetime)) {
      $(this).text(inWords(data.datetime));
    }
    return this;
  }

  function prepareData(element) {
    element = $(element);
    if (!element.data("timeago")) {
      element.data("timeago", { datetime: $t.datetime(element) });
      var text = $.trim(element.text());
      if (text.length > 0) {
        element.attr("title", text);
      }
    }
    return element.data("timeago");
  }

  function inWords(date) {
    return $t.inWords(distance(date));
  }

  function distance(date) {
    return (new Date().getTime() - date.getTime());
  }

  // fix for IE6 suckage
  document.createElement("abbr");
  document.createElement("time");
}(jQuery));

/*
 * Date Format 1.2.3
 * (c) 2007-2009 Steven Levithan <stevenlevithan.com>
 * MIT license
 *
 * Includes enhancements by Scott Trenda <scott.trenda.net>
 * and Kris Kowal <cixar.com/~kris.kowal/>
 *
 * Accepts a date, a mask, or a date and a mask.
 * Returns a formatted version of the given date.
 * The date defaults to the current date/time.
 * The mask defaults to dateFormat.masks.default.
 */

var dateFormat = function () {
	var	token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
		timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
		timezoneClip = /[^-+\dA-Z]/g,
		pad = function (val, len) {
			val = String(val);
			len = len || 2;
			while (val.length < len) val = "0" + val;
			return val;
		};

	// Regexes and supporting functions are cached through closure
	return function (date, mask, utc) {
		var dF = dateFormat;

		// You can't provide utc if you skip other args (use the "UTC:" mask prefix)
		if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
			mask = date;
			date = undefined;
		}

		// Passing date through Date applies Date.parse, if necessary
		date = date ? new Date(date) : new Date;
		if (isNaN(date)) throw SyntaxError("invalid date");

		mask = String(dF.masks[mask] || mask || dF.masks["default"]);

		// Allow setting the utc argument via the mask
		if (mask.slice(0, 4) == "UTC:") {
			mask = mask.slice(4);
			utc = true;
		}

		var	_ = utc ? "getUTC" : "get",
			d = date[_ + "Date"](),
			D = date[_ + "Day"](),
			m = date[_ + "Month"](),
			y = date[_ + "FullYear"](),
			H = date[_ + "Hours"](),
			M = date[_ + "Minutes"](),
			s = date[_ + "Seconds"](),
			L = date[_ + "Milliseconds"](),
			o = utc ? 0 : date.getTimezoneOffset(),
			flags = {
				d:    d,
				dd:   pad(d),
				ddd:  dF.i18n.dayNames[D],
				dddd: dF.i18n.dayNames[D + 7],
				m:    m + 1,
				mm:   pad(m + 1),
				mmm:  dF.i18n.monthNames[m],
				mmmm: dF.i18n.monthNames[m + 12],
				yy:   String(y).slice(2),
				yyyy: y,
				h:    H % 12 || 12,
				hh:   pad(H % 12 || 12),
				H:    H,
				HH:   pad(H),
				M:    M,
				MM:   pad(M),
				s:    s,
				ss:   pad(s),
				l:    pad(L, 3),
				L:    pad(L > 99 ? Math.round(L / 10) : L),
				t:    H < 12 ? "a"  : "p",
				tt:   H < 12 ? "am" : "pm",
				T:    H < 12 ? "A"  : "P",
				TT:   H < 12 ? "AM" : "PM",
				Z:    utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
				o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
				S:    ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
			};

		return mask.replace(token, function ($0) {
			return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
		});
	};
}();

// Some common format strings
dateFormat.masks = {
	"default":      "ddd mmm dd yyyy HH:MM:ss",
	shortDate:      "m/d/yy",
	mediumDate:     "mmm d, yyyy",
	longDate:       "mmmm d, yyyy",
	fullDate:       "dddd, mmmm d, yyyy",
	shortTime:      "h:MM TT",
	mediumTime:     "h:MM:ss TT",
	longTime:       "h:MM:ss TT Z",
	isoDate:        "yyyy-mm-dd",
	isoTime:        "HH:MM:ss",
	isoDateTime:    "yyyy-mm-dd'T'HH:MM:ss",
	isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};

// Internationalization strings
dateFormat.i18n = {
	dayNames: [
		"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
		"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
	],
	monthNames: [
		"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
		"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
	]
};

// For convenience...
Date.prototype.format = function (mask, utc) {
	return dateFormat(this, mask, utc);
};


function flickr_set(set_id){

		if (typeof(set_id)=='object'&&(set_id instanceof Array)) {
		
			$(".flickr").append('<div class="banner-box"><div class="banner-bottom-left-corner"></div><div class="banner-bottom-right-corner"></div><div class="banner-top-left-corner"></div><div class="banner-top-right-corner"></div><div class="banner clearfix"><div class="radial"><div class="stitching clearfix"><div class="col c10"><div class="photo-gallery"></div></div></div></div>');
			
			var li_text = new Array();
			
			for (k = 0; k < set_id.length; k++) {
			
				var j = k;
			
				var href = "http://api.flickr.com/services/rest/?format=json&method=flickr.photosets.getPhotos&photoset_id=" + set_id[k] + "&per_page=9&page=1&api_key=d05c402deb15a84b8c93461a018ac2ef&jsoncallback=?";
				
				li_text[k] = $("ul.facilities li:eq("+k+")").html();
				
				$(".photo-gallery").append('<h2>Photo Gallery from ' + li_text[k] + '</h2><h3><a href="http://www.flickr.com/photos/pinkglovedance/sets/' + set_id[k] + '" target="_blank">View the full set and leave comments on Flickr &rarr;</a></h3><div class="gallery-box box'+set_id[k]+' clearfix"></div>');
				
				$.getJSON(href, function(data){
	
					$.each(data.photoset.photo, function(i, photo){
		
						var img = '<a href="http://www.flickr.com/photos/' + data.photoset.owner + '/' + photo.id + '/" target="_blank"><img src="http://farm' + photo.farm + '.static.flickr.com/' + photo.server + '/' + photo.id + '_' + photo.secret + '_' + 's.jpg" width="75" height="75" alt="' + photo.title + '" /></a>';
						
						$(".box" + data.photoset.id).append(img);
						
					});
		
				});
				
			}
			
		} else {

			var href = "http://api.flickr.com/services/rest/?format=json&method=flickr.photosets.getPhotos&photoset_id=" + set_id + "&per_page=9&page=1&api_key=d05c402deb15a84b8c93461a018ac2ef&jsoncallback=?";
			
			var h1_text = $("h1").html();
			
			$(".flickr").append('<div class="banner-box"><div class="banner-bottom-left-corner"></div><div class="banner-bottom-right-corner"></div><div class="banner-top-left-corner"></div><div class="banner-top-right-corner"></div><div class="banner clearfix"><div class="radial"><div class="stitching clearfix"><div class="col c10"><div class="photo-gallery"><h2>Photo Gallery from ' + h1_text + '</h2><h3><a href="http://www.flickr.com/photos/pinkglovedance/sets/' + set_id + '" target="_blank">View the full set and leave comments on Flickr &rarr;</a></h3></div></div></div></div>');
	
			$.getJSON(href, function(data){
	
				$.each(data.photoset.photo, function(i, photo){
	
					var img = '<a href="http://www.flickr.com/photos/' + data.photoset.owner + '/' + photo.id + '/" target="_blank"><img src="http://farm' + photo.farm + '.static.flickr.com/' + photo.server + '/' + photo.id + '_' + photo.secret + '_' + 's.jpg" width="75" height="75" alt="' + photo.title + '" /></a>';
					
					$(".photo-gallery").append(img);
					
				});
	
			});
			
		}

};
