/* YUI Utility Extensions */


YAHOO.util.Dom.comment = function (str) { 
	return "<" + "!-- " + str + " --" + ">"; 
};

String.prototype.trim = function () {
	return this.replace(/^\s*/, "").replace(/\s*$/, "");
}

/* http://jonefox.com/blog/2009/05/21/internet-explorer-and-the-innerhtml-property/ */
YAHOO.util.Dom.setInnerHTML = function (el, html) {
	if( el ) {
		var oldEl = (typeof el === "string" ? document.getElementById(el) : el);
		var newEl = document.createElement(oldEl.nodeName);
		
		// Preserve any properties we care about (id and class in this example)
		newEl.id = oldEl.id;
		newEl.className = oldEl.className;
		
		//set the new HTML and insert back into the DOM
		newEl.innerHTML = html;
		if(oldEl.parentNode)
			oldEl.parentNode.replaceChild(newEl, oldEl);
		else
			oldEl.innerHTML = html;
		
		//return a reference to the new element in case we need it
		return newEl;
	}
};


YAHOO.util.Dom.setFlashVisibility = function ( visibleness ) {
	if (visibleness !== null) {
		for (var tagNames = new Array("object", "embed", "video", "iframe"), tg = 0; tg < tagNames.length; tg++) {
			flashes = document.body.getElementsByTagName(tagNames[tg]);
			if (flashes) {
				for (var i = 0; i < flashes.length; i++) {
					YAHOO.util.Dom.setStyle(flashes[i],"visibility", (visibleness ? "visible" : "hidden") );
				}
			}
		}
	} else {
		//window.alert("flash visibility param must be true or false");
	}
}



/* adapted from http://geekswithblogs.net/aghausman/archive/2008/10/30/how-to-remove-html-tags-from-a-string-in-javascript.aspx */
if (!String.prototype.stripHTMLTags) {
	String.prototype.stripHTMLTags = function() {
		var tempDiv = document.createElement("div");
		tempDiv.innerHTML = this;
		if (document.all) {
			// IE stuff
			return tempDiv.innerText;
		} else {
			// Mozilla does not work with innerText
			return tempDiv.textContent;
		}
	}
}


if (!Number.prototype.twoDigit) {
	Number.prototype.twoDigit = function() {
		if (this < 10 && this > -10)
			return "0" + this.toString();
		else
			return this.toString();
	};
};

if (!Date.prototype.format) {
	Date.prototype.format = function(fmt) {
		var MONTHS_SHORT = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
			WEEKDAYS_MEDIUM = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
			AM = "am", PM = "pm", NOON = "noon", MIDNIGHT = "midnight",
			COMMA_SPACE = ", ", SPACE = " ", SLASH = "/", COLON = ":", SP_2DASH_SP = " -- ";

		if (typeof fmt != "string")
			throw new TypeError();
		
		switch (fmt) {
			case "yyyymm": 
				return this.getFullYear().toString() + (this.getMonth()+1).twoDigit(); 
				break;
			case "yyyymmdd": 
				return this.getFullYear().toString() + (this.getMonth()+1).twoDigit() + this.getDate().twoDigit(); 
				break;
			case "m/d/yyyy": 
				return (this.getMonth()+1).toString() + SLASH + this.getDate() + SLASH + this.getFullYear(); 
				break;
			case "WMDY-short": 
				return WEEKDAYS_MEDIUM[this.getDay()] + COMMA_SPACE + 
					MONTHS_SHORT[this.getMonth()] + SPACE + 
					this.getDate() + COMMA_SPACE + this.getFullYear(); 
				break;
			case "WMDY--H:Ma": 
				return WEEKDAYS_MEDIUM[this.getDay()] + COMMA_SPACE + 
					MONTHS_SHORT[this.getMonth()] + SPACE + 
					this.getDate() + COMMA_SPACE + this.getFullYear() +
					SP_2DASH_SP + ((this.getHours() + 11) % 12 + 1) + 
					((this.getMinutes() >= 0) ? (COLON + this.getMinutes().twoDigit()) : "") +
					SPACE + ((this.getHours() < 12) ? AM : PM); 
				break;
			case "H:Ma": 
				return ((this.getHours() + 11) % 12 + 1) + 
					((this.getMinutes() >= 0) ? (COLON + this.getMinutes().twoDigit()) : "") + 
					((this.getHours() < 12) ? AM : PM);
				break;
		}
	};
};

if (!Array.prototype.format)
{
  Array.prototype.format = function(fmt)
  {
    var len = this.length, MDY_SEPARATOR = "/";
    if (typeof fmt != "string")
      throw new TypeError();
    switch (fmt) {
      /* handle date when given array of [year, month, day], as YAHOO.widget.Calendar tends to do */
      case "m/d/yyyy":
        return this[1] + MDY_SEPARATOR + this[2] + MDY_SEPARATOR + this[0]; break;
      default:
        return ""; break;
    }
  };
};


// from http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Objects:Array:filter
if (!Array.prototype.filter)
{
  Array.prototype.filter = function(fun /*, thisp*/)
  {
    var len = this.length;
    if (typeof fun != "function")
      throw new TypeError();

    var res = new Array();
    var thisp = arguments[1];
    for (var i = 0; i < len; i++)
    {
      if (i in this)
      {
        var val = this[i]; // in case fun mutates this
        if (fun.call(thisp, val, i, this))
          res.push(val);
      }
    }

    return res;
  };
};

// http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Objects:Array:forEach
if (!Array.prototype.forEach)
{
  Array.prototype.forEach = function(fun /*, thisp*/)
  {
    var len = this.length;
    if (typeof fun != "function")
      throw new TypeError();

    var thisp = arguments[1];
    for (var i = 0; i < len; i++)
    {
      if (i in this)
        fun.call(thisp, this[i], i, this);
    }
  };
};

// http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Objects:Array:map
if (!Array.prototype.map)
{
  Array.prototype.map = function(fun /*, thisp*/)
  {
    var len = this.length;
    if (typeof fun != "function")
      throw new TypeError();

    var res = new Array(len);
    var thisp = arguments[1];
    for (var i = 0; i < len; i++)
    {
      if (i in this)
        res[i] = fun.call(thisp, this[i], i, this);
    }

    return res;
  };
};

/*
	parseUri 1.2.1
	(c) 2007 Steven Levithan <stevenlevithan.com>
	MIT License
*/
function parseUri (str) {
	var	o   = parseUri.options,
		m   = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
		uri = {},
		i   = 14;
	while (i--) uri[o.key[i]] = m[i] || "";
	uri[o.q.name] = {};
	uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
		if ($1) uri[o.q.name][$1] = $2;
	});
	return uri;
};
parseUri.options = {
	strictMode: false,
	key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
	q:   {
		name:   "queryKey",
		parser: /(?:^|&)([^&=]*)=?([^&]*)/g
	},
	parser: {
		strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
		loose:  /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
	}
};


// form validation from http://agilewebmasters.com/nick/javascript-form-validation-object/
function Validator()
{
}
/**
 *  Check Email Function
 */
Validator.prototype.checkEmail=function(ELEM, EVENT)
{
	if(EVENT) {
		var scope = this;
		YAHOO.util.Event.addListener(ELEM, EVENT, function(){scope.checkEmail(ELEM);});
		return false;
	}
	try {
		var elem = new YAHOO.util.Element( ELEM );
		var targetElem = new YAHOO.util.Element( ELEM + "_error" );
		var email = elem.value;
		var regex = /^[-_.a-zA-Z0-9]+@[-_.a-zA-Z0-9]+\.[a-zA-Z0-9]+$/;
		if (regex.test(email)) {
			targetElem.className = "error-text-hidden";
			return true;
		} else {
			targetElem.innerHTML = "please enter a valid email address";
			targetElem.className = "error-text";
			return false;
		}
	}
	catch(e) {
		alert("Error in Validator() -> checkEmail(): " + e.message);
		return false;
	}
};




/*
 * Special event for image load events
 * Needed because some browsers does not trigger the event on cached images.

 * MIT License
 * Paul Irish     | @paul_irish | www.paulirish.com
 * Andree Hansson | @peolanha   | www.andreehansson.se
 * 2010.
 *
 * Usage:
 * $(images).bind('load', function (e) {
 *   // Do stuff on load
 * });
 * 
 * Note that you can bind the 'error' event on data uri images, this will trigger when
 * data uri images isn't supported.
 * 
 * Tested in:
 * FF 3+
 * IE 6-8
 * Chromium 5-6
 * Opera 9-10
 */
(function ($) {
	$.event.special.load = {
		add: function (hollaback) {
			if ( this.nodeType === 1 && this.tagName.toLowerCase() === 'img' && this.src !== '' ) {
				// Image is already complete, fire the hollaback (fixes browser issues were cached
				// images isn't triggering the load event)
				if ( this.complete || this.readyState === 4 ) {
					hollaback.handler.apply(this);
				}

				// Check if data URI images is supported, fire 'error' event if not
				else if ( this.readyState === 'uninitialized' && this.src.indexOf('data:') === 0 ) {
					$(this).trigger('error');
				}
				
				else {
					$(this).bind('load', hollaback.handler);
				}
			}
		}
	};
}(jQuery));


/* 
PHOTO CONTAINER AUTOSIZE
Assigns width to inset image's container div.
Makes sure photo credit and caption divs don't stretch the container div.
- P.Cho 9/30/10
*/

$(document).ready(function() {
	
	var imgDivs = $('.image-inset');

	imgDivs.each(function() {
						
		var imgDiv = $(this); /* Assign to variable so works within scope of upcoming function */
		var img = imgDiv.find('img:eq(0)'); /* Use 'find' instead of 'children' for cases where img is wrapped in an <a> */

		/* Uses ahpi.imgload.js plugin to check if img has loaded first - either from src or from cache */
		$(img).bind('load', function () {
			var imgW = img.width();
			if (imgW > 0) {
				imgDiv.width(imgW + 2); /* Add 2px to accommodate img border */
			}
		});
						
	});
	
});



/* 
FANCYBOX
Lightbox overlay
- P.Cho 11/8/10
*/

/* Adds an extra "close" link to the lightbox */
function formatTitle(title, currentOpts) {
	return '<a class="link-close" href="javascript:;" onclick="$.fancybox.close();">Close</a>' + (title && title.length ? title : '' );
}

$(document).ready(function() {

	/* Apply Fancybox to all <a> tags that have rel="lightbox" */
	$("a[rel=lightbox]").fancybox({
		'titlePosition'				: 'inside',
		'showNavArrows'				: false,
		'hideOnContentClick'	: true,
		'padding'							: 20,
		'margin'							: 80,
		'margin'							: 80,
		'overlayColor'				: '#000',
		'overlayOpacity'			: 0.6,
		'titleFormat'					: formatTitle
	});
	
	
	/* Checks photo to see if actual size > displayed size. 
	If true, then activate lightbox feature. 
	P.Cho 11/12/10 */
	/* Updated 2/23/10 P.Cho */
	var photoDivs = $('.inset-photo');

	photoDivs.each(function() {
		
		var photoDiv = $(this); /* Assign to variable so works within scope of upcoming function */
		var photoImg = photoDiv.find('img.photo:eq(0)');
		var imgSrc = photoImg.attr('src');

		var imgCSSW = photoImg.width(); /* Displayed width of photo */
		var imgRealW; /* Actual width of photo */

		/* Uses ahpi.imgload.js plugin to check if img has loaded first - either from src or from cache */
		$(photoImg).bind('load', function () {
	    /* Remove CSS width to find actual width of photo.
	    Can't use "new Image()" to create a hidden instance of photo. Breaks in FF on live server */
	    $(this).css('width' , 'auto');
	    imgRealW = this.width;
		});
		
		var src = photoImg.src;
		photoImg.css('width' , imgCSSW); /* Restore display width to photo */

		/* If real image is larger, provide lightbox feature */
		if (imgRealW > imgCSSW) {
			/* Show enlarge link */
			photoDiv.find('.bu-enlarge').show();
			/* Turn photo into a lightbox link.*/
			$(photoImg).css('cursor','pointer');
			$(photoImg).fancybox({
				'titlePosition'				: 'inside',
				'showNavArrows'				: false,
				'hideOnContentClick'	: true,
				'padding'							: 20,
				'margin'							: 80,
				'overlayColor'				: '#000',
				'overlayOpacity'			: 0.6,
				'titleFormat'					: formatTitle,
				'href'								: imgSrc
			});
		}

	});

});

