//
// This file requires jQuery
//

/**
 * Alters heights of provided div elements so that bottoms align;
 * 
 * @param {jQuery} divs A jQuery array containing the divs to align
 * @author L Reinhard (10-21-2008)
 * 
 * @example addScriptBlock("$(document).ready(function(){alignBottoms($('##primary,##secondary,##tertiary'))})");
 */

function alignBottoms(divs) {
	
	var MaxBottom = 0;
	
	if (divs.length > 1) {
		divs.each(function() {
			var div = $(this);
			MaxBottom = Math.max(MaxBottom,div.outerHeight(true) + div.position().top); 
		});
		divs.each(function() {
			var div = $(this);
			div.height(MaxBottom - div.position().top - div.outerHeight(true) + div.height()) + 'px';
		});
	}
}

function hoverEffect(obj) {
	if (! obj.hoverDone){
		obj.onmouseover = new Function("this.className = '"+obj.className+" "+obj.className+"_hover';");
		obj.onmouseout = new Function("this.className = '"+obj.className+"';");
		obj.hoverDone = 1;
	}
	return 0;
}

function hoverEffectRemove(obj) {
	if (obj.hoverDone){
		obj.onmouseover = null;
		obj.onmouseout = null;
		obj.hoverDone = 0;
	}
	return 0;
}

function setImageOpacityOn() {
	var t,i;
	// The initial opacity. MSIE takes 0-100 values for opacity. All others take floating points.
	initialOpacity=document.all?50:.5;
	// Make a very simple check for arguments and argument type
	if(arguments.length > 0 && typeof arguments[0] == 'string') {
		for (i = 0; i < arguments.length; i++) {
			if(document.getElementById)t=document.getElementById(arguments[i]);else t=document.all(arguments[i]);
			if(t!=null) {
				// set the opacity of the object. Once for Gecko, once for Safari and once for MSIE.
				t.style.filter="alpha(opacity=" + initialOpacity + ")";
				t.style.MozOpacity=initialOpacity;
				t.style.opacity=initialOpacity;
			}
		}
	}
}

function ForceIE6Overlay() {
	var t,b,HoldHeight;
	t = document.getElementById('overlay-frame');
	if(t!=null) {
		HoldHeight = t.offsetHeight;
		b=document.getElementById('overlay-body');
		if(b!=null) {
			b.style.height=HoldHeight;
		}
	}
}

// Automatically apply col text-align's to table column td's if table has class ApplyColumnAlign
function ApplyColumnAlign() {
	$("TABLE.ApplyColumnAlign").each(
		function() {
			var thisTable = this;
			$(">COLGROUP>COL",thisTable).each(
				function(i) {
					var colAlign = $(this).css("text-align");
					if (colAlign == "left" || colAlign == "right"  || colAlign == "center" ) {
						// the stupid append of an empty "span" below is to force ie8 to render when align!=<objects-current-align>
						$(">TBODY>TR>TD:nth-child(" + (i+1) + ")",thisTable).css("text-align",colAlign).append("<span />");
					}
				}
			);
		}
	);
}

// This is not used yet but will be for dynamically 
//   adding the hover effect in IE6 to elements other than anchor tags
function ApplyHoverForIE6() {
	if ($.browser.msie && (jQuery.browser.version <= 7)) {
		var reg = /_hover$/;
		$.each (document.styleSheets, function(){
			// really only "rules" is needed since it's IE
			$.each (this.cssRules || this.rules, function() {
		    	if (reg.test(this.selectorText)) alert(this.style.cssText);
				// this.style.cssText
				// exp: expression(hoverEffect(this));
			});
		});
	}
}

function PictureFrameLoader () {
	$("div.PictureFrame img").each(function(){
		if (this.complete) {
			PictureFrameImageResize(this);
		} else {
			$(this).load(function(){ PictureFrameImageResize(this); })
		}
	});
}

/**
 * Resizes the given image and centers it horizontally and vertically
 * using margins. Since the current image dimensions are used to compute
 * the proper aspect ratio (thanks to IE), the image should be
 * undistorted when being passed to this function (preferably the
 * original size). For this reason, the visibility is restored in case
 * the orginal image is hidden.
 */
function PictureFrameImageResize (FrameImage) {
	if (FrameImage.style.visibility != 'visible') {
		var PictureFrame = $(FrameImage).parent().get(0);
		var imgh = $(PictureFrame).height();
		var imgw = $(PictureFrame).width();
		
		var w = FrameImage.width;
		var h = FrameImage.height;

		if (!w || !h || !imgh || !imgw) return;

		// Set the dimensions
		if (w >= h && w > imgw) {
			FrameImage.width = imgw;
			FrameImage.height = (h*imgw/w);
		} else if (h > imgh) {
			FrameImage.height = imgh;
			FrameImage.width= (w*imgh/h);
		}
		
		// Set the margins
		FrameImage.style.margin = (imgh-FrameImage.height)/2 + "px " + (imgw-FrameImage.width)/2 + "px";
		
		// Remove the spinner class from the picture frame
		$(PictureFrame).removeClass('Spinner');
		
		// Make the picture frame image visible (if the parent is visible)
		FrameImage.style.visibility = 'inherit';
	}
}

/*
 * Assumes that you have stored the URL to the full size image
 * in the thumbs alt.
 * Will pick up tool-tip and place in div after PictureFrame.
 * Will pick up any controls and place in div after PictureFrame (and tooltip).
 * This function requires the jQuery 'simplemodal' plugin.
 */
function PictureFrameZoomer (zoomMinHeight,zoomMinWidth) {
	if (typeof(zoomMinHeight) == 'undefined')
		zoomMinHeight = 485;
	if (typeof(zoomMinWidth) == 'undefined')
		zoomMinWidth = 400;
	$("div.PictureFrame").click(function (e) {
		var zoomFrame = $(this).clone().attr('id','PictureFrameZoom');
		var	img = new Image();
		$(img).attr('src',zoomFrame.children('img').attr('alt'));
		zoomFrame.children('img').replaceWith(img);
		$(img).load(function(){ PictureFrameImageResize(this); })
		// ie won't fire onload if image is already loaded
		if (img.complete) PictureFrameImageResize(img);
		zoomFrame.modal({
			minHeight: zoomMinHeight,
			minWidth: zoomMinWidth,
			onShow:function(){ PictureFrameImageResize(img); }
		});
		// add label to top
		var imgLabel = $('label', $(this).parent());
		if (imgLabel.size()) {
			zoomFrame.before(imgLabel.clone().addClass('PictureFrameTitle'));
		}
		// add tooltip if any to modal dialog
		var imgInformation = $(this).next('.show-tooltip-text');
		if (imgInformation.attr('class') == 'show-tooltip-text') {
			imgInformation = $('<div/>').html(imgInformation.html())
								.addClass('PictureFrameInformation');
			zoomFrame.after(imgInformation);
		}
		// add any controls
		var imgControls = $('.PictureFrameControls');
		if (imgControls.size()) {
			imgControls = $('<div id="PictureFrameControls"/>').html(imgControls.html());
			zoomFrame.after(imgControls);
		}
	});
}

/*
 * Assumes that you have stored the URL to the full size image
 * in the thumbs alt.
 * This function requires the jQuery 'simplemodal' plugin.
 */
function PictureZoomer () {
	$("div.PictureFrame img").click(function (e) {
		var img = new Image(); // must create img obj this way for IE height/width to work.
		$(img).attr('src',$(this).attr('alt'));
		if (img.complete) {
			PictureZoom(img);
		} else {
			$(img).load(function(){ PictureZoom(this); })
		}
	});
}

/* 
 * Zooms a picture to a modal window of a given max size.
 * Should be called 'onload' of image or if image.complete
 *  (note IE does not call 'onload' if pulling image from cache)
 * This function requires the jQuery 'simplemodal' plugin.
 * 
 */ 
function PictureZoom(Image,MaxSize) {
	var w = Image.width;
	var h = Image.height;
	
	if (!MaxSize) MaxSize = 360;
	
	if (!w || !h) {
		// image problem
	} else if (w > h) {
		w = Math.min(w,MaxSize);
		h = parseInt(h*(w/Image.width))
	} else {
		h = Math.min(h,MaxSize);
		w = parseInt(w*(h/Image.height))
	}
	$(Image).height(h).width(w).modal({containerCss:{height:h, width:w}});
}


/**
 * These functions allow for html tooltips. You can further enhance
 * 
 */
function SetupTooltips() {
	$('.show-tooltip')
		.each(function(){
			$(this)
				.after($('<span/>')
					.attr('style', 'display:none;position:absolute;')
					.attr('class', 'show-tooltip-text')
					.html($(this).attr('title')))
				.attr('title', '');
		})
		.hover(ShowTooltip, HideTooltip)
		.mousemove(MoveTooltip);
}
function ShowTooltip(e) {
	var text = $(this).next('.show-tooltip-text');
	if (text.attr('class') != 'show-tooltip-text')
		return false;

	// stop other tips etc.
	e.preventDefault();

	// use the animate function to delay appearance .animate({opacity:1.0}, 1000)
	text.fadeIn()
		.css('top', e.pageY+5)
		.css('left', e.pageX+5);

	return false;
}
function HideTooltip(e) {
	var text = $(this).next('.show-tooltip-text');
	if (text.attr('class') != 'show-tooltip-text')
		return false;

	text.hide();
}
function MoveTooltip(e) {
	var text = $(this).next('.show-tooltip-text');
	if (text.attr('class') != 'show-tooltip-text')
		return false;

	// stop other tips etc.
	e.preventDefault();

	text.css('top', e.pageY+5)
		.css('left', e.pageX+5);

	return false;
}



// Sets an input field's value to its default
function InputResetToDefault (FieldType, FieldName) {
	var FormFields = $("input[type='"+FieldType+"'][name='"+FieldName+"']");
	$(FormFields).each(function(){
		this.value="";
		//Doesn't exactly solve our problem, the new property is lost on form submit:
		/*if (this.OriginalValue==null) {
			this.OriginalValue=this.defaultValue;
		} else {
			this.value=this.OriginalValue;
		}*/
		//Doesn't work for hidden input fields:
		/*this.value=this.defaultValue;*/
	});
}

// Created By: Albert Hailes
//
// This script scales all images within the specified DIV enough to neatly fit
//   the specified DIV within its parent container (usually a DIV).
// 
//	02/09/2009   AL    Changed the default sizing method to 'fit-in-table' (when there is a child table)
//                     Added '-ms-interpolation-mode:bicubic;' for IE7 smooth image scaling
//                     Added 'image-rendering:optimizeQuality;' for Firefox 3.6 smooth image scaling
//
// Parameters: 
//   DivId     - DIV Unique ID
//   MaxWidth  - Maximum width (Optional), default is the parents width
//
// Example Usage: 
//   ForceDivWidth('webpagesizer','520')
//
function ForceDivWidth(DivId) {
	var i,MaxWidth,thisParentNode,parentDIVWidth,thisDIVWidth,reduceBy,recalcWidth,childImages,cellOffset;
	var retryCount = 1;
	var ImagesLoaded = true;
	var sizingMethod = 'fit-in-table';	// 'scale','fit-in-table'
	var primaryTable = 0;
	var totalCols = 0;
	
	if(!$("div#"+DivId+" img").length)return;	// No images so we're done
	thisParentNode = $("div#"+DivId).parent();
	if(arguments.length > 1 && typeof arguments[1] == 'string') {
		MaxWidth = arguments[1];
	} else {
		MaxWidth = thisParentNode.get(0).offsetWidth;
	}
	// Test that all target images are loaded
	$("div#"+DivId+" img").each(function(){
		if (this.complete==false) {
			ImagesLoaded = false;
			return false;	// break out of 'each' iteration
		}
	});
	if (!ImagesLoaded) {
		setTimeout('ForceDivWidth("'+DivId+'",'+MaxWidth+');', 200);
		return;
	}
	if(arguments.length > 2 && typeof arguments[2] == 'number') {
		retryCount = arguments[2];
	}
	retryCount = retryCount + 1;
	$("div#"+DivId).css({display:'inline'});		// Ensure it is NOT 'display:block;'
	// Save the fixed parent width (usually a DIV too) and the current unfixed width
	parentDIVWidth = MaxWidth;
	thisDIVWidth = thisParentNode.get(0).scrollWidth;
	if(thisDIVWidth>parentDIVWidth) {
		// Since this is larger than the parent, we resize the IMAGES
		if (sizingMethod == 'fit-in-table' && $("div#"+DivId+" table").length) {
			// This sizing method requires that there be at least one child table
			primaryTable = $("div#"+DivId+" img:first").parents().filter("table:first").addClass(DivId + "fit-in-table");
			// Get number of columns in table
			$("tr td:last",primaryTable).each(function () {
				var colIndex = $(this).prevAll().length + 1;
				if (colIndex > totalCols) { totalCols = colIndex; }
			});
			// Use the position offset of the 1st image inside the table for a best guess at the table's cellpadding, cellspacing, border, etc.
			cellOffset = (( $("table."+DivId+"fit-in-table img:first").position().left - $("table."+DivId+"fit-in-table").position().left ) + 1) * 2;
			recalcWidth = Math.floor((parentDIVWidth-(cellOffset*totalCols))/totalCols);
			childImages = $("div#"+DivId+" img");
			for (var i=0; i<childImages.length; i++) {
				if (childImages.get(i).width > recalcWidth) {
					childImages.get(i).style.cssText = 'width:'+ Math.floor(recalcWidth) +'px;height:auto;-ms-interpolation-mode:bicubic;image-rendering:optimizeQuality;';
				}
			}
			thisParentNode.get(0).style.cssText = 'width:' + MaxWidth +'px;height:auto;overflow:hidden;';
		} else {
			// Same as sizingMethod:'scale' (the original behavior)
			reduceBy = parentDIVWidth/thisDIVWidth;				// Percentage to reduce by
			// Adjust the sizes of all children images
			childImages = $("div#"+DivId+" img");
			for (var i=0; i<childImages.length; i++) {
				recalcWidth = childImages.get(i).width;
				recalcWidth = recalcWidth * reduceBy;
				childImages.get(i).style.cssText = 'width:'+ Math.floor(recalcWidth) +'px;height:auto;-ms-interpolation-mode:bicubic;image-rendering:optimizeQuality;';
			}
			thisParentNode.get(0).style.cssText = 'width:' + MaxWidth +'px;height:auto;overflow:hidden;';
			// Just in case it is still a tiny amount too big (insufficient precision)
			if (thisParentNode.get(0).scrollWidth>parentDIVWidth && retryCount<4) { ForceDivWidth(DivId,MaxWidth,retryCount); }
		}
	}
}


$(document).ready(ApplyColumnAlign);

