//
// Copyright (c) 2011, Algin Technology LLC.  All Rights Reserved.
//
// $Id: Algin-jquery.js,v 1.2 2011/05/29 04:14:20 cvsalan Exp $
//
// Paste into http://www.jslint.com/ to verify
/*jslint browser: true, undef: true, regexp: true, bitwise: true, newcap: true, maxerr: 50, indent: 4 */
/*global $ */

var oAlgin = {};

// Prevent background images from flickering in IE6 due
// to repeated reloads from the server
(function () {
	var badBrowser = $.browser.msie && /MSIE (6|7)/.test(navigator.userAgent);
	if (badBrowser) {
		try {
			// IE6 SP1 or IE7.  Fails on IE6 SP0.
			document.execCommand("BackgroundImageCache", false, true);
		} catch (e) {}
	}
}()); // invoke immediately (dont defer until ready)


///////////////////////////////////////////////////////////////////////////
//
// Deferred script follows. These functions are all called during
// the ready event, when all DOM elements are accessible (but images
// are not yet loaded).
//
// $(function () {..}) is preferred over $(document).ready(function() {..})
//

//(function ($) { // Uncomment to avoid .noConflict()
//
// Determine oAlgin.rootUrl.  Must be first.
// BUG: Assumes the path components 'inc\Algin' are hardcoded.
//
$(function () {
	$('script[src*=lgin]').each(function () { // Only MSIE has document.scripts
		var src = this.src;
		if (src) { // "file:///C:/inetpub/wwwroot/UTools2/inc/Algin-jquery.js"
			var iPos = src.toLowerCase().lastIndexOf("inc/algin");
			if (iPos >= 0) {
				oAlgin.rootUrl = src.slice(0, iPos); // "file:///C:/inetpub/wwwroot/UTools2/"
				//alert(oAlgin.rootUrl);
				return false; // break out of each()
			}
		}
	});
});
//
// Arrange to kick off the lavalamp
//
oAlgin.doLavaLamp = function () {
	// lava lamp
	$('#nav ul.nav').lavaLamp({
		fx: 'easeOutBack',
		speed: 1000
	});
};
//
// Fire any actions that are deferred until after all ready animations 
// are done (such as fading-in the web page). 
//
// We must defer the LavaLamp because it doesn't work if hide() is 
// being fired simultaneously in Webfont.load().
// 
oAlgin.onReadyAnimationDone = function () {
	oAlgin.doLavaLamp();
};
//
// Fix PNG images on MSIE 5.5 and 6.0 (incl 7.0 for testing)
//
$(function () {
	// See http://docs.jquery.com/Tutorials:PNG_Opacity_Fix_for_IE6
	var badBrowser = $.browser.msie 
		&& /MSIE ((5\.5)|6|7)/.test(navigator.userAgent)
		&& navigator.platform.substr(0, 3) === 'Win';
	if (badBrowser) {
		if (!oAlgin.imgBlank) { // Load the blank 1x1 shim
			oAlgin.imgBlank = new Image();
			oAlgin.imgBlank.src = oAlgin.rootUrl + 'images/1x1blank.gif';
		}
		// Find all png images and arrange to fix 
		$('img[src$=png]').each(function () {
			if (!this.complete) { // if image not loaded yet, defer until load
				this.onload = function () { oAlgin.fixPng(this); };
			} else {
				oAlgin.fixPng(this);
			}
		});
	}
});
oAlgin.fixPng = function (png) {
	// set width and height
	if (!png.style.width) { png.style.width = $(png).width() + "px"; }
	if (!png.style.height) { png.style.height = $(png).height() + "px"; }
	var src = png.src; // save orig src path
	png.onload = function () { }; // prevent recursion on next line
	png.src = oAlgin.imgBlank.src; // replace with blank 1x1 gif
	// Alt sizingMethod='image','crop','scale'
	png.runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "',sizingMethod='scale')";
};
//
// Add <body scroll="auto"> for IE6 (nonstandard attrib)
// IE8+ and standard browsers ignore it.
// 
$(function () {
	if ($.browser.msie && navigator.platform.substr(0, 3) === 'Win') {
		if (/MSIE (6|7)/.test(navigator.userAgent)) {
			$('body').attr('scroll', 'auto');
		}
		/* WRONG - Testing shows we need scroll="auto" on IE6
		if (/MSIE 6/.test(navigator.userAgent)) {
			$('body').removeAttr('scroll');
		}
		*/
	}
});
//
// Remove and re-insert the gray 'Search' text in the #search textbox
// whenever the textbox gets or loses focus.
// 
$(function () {
	var search = $('#SearchString');
	search.val('Search'); // Initial text
	search.css('color','#AAAAAA');
	search.focus(function(){
		if ($(this).val() === 'Search') {
			$(this).val('');
			search.css('color','black');
		}
	}).blur(function() {
		if ($(this).val() === '') {
			search.css('color','#AAAAAA');
			$(this).val('Search');
		}
	});
});
//
// Implement "display: table;" and "display: table-cell;" on IE 5-7
// by inserting actual <table> and <td> elements at runtime.
//
// BUG: Doesn't work if the user turns off JavaScript (e.g., running
// in Enhanced Security Configuration on Windows Server, pre W2K8R2.)
//
// Change <div class="pseudo-table"><div class="pseudo-td">Centered Text</div></div>
// to
// <table width="100%"><tbody><tr><div class="pseudo-table">
//  <td class="pseudo-td"><div class="pseudo-td">Centered text1</div></td>
//  <td class="pseudo-td"><div class="pseudo-td">Centered text2</div></td>
// </div></tr></tbody</table>
//
// We hoist up the div's CSS settings for vertical-align and text-align.
//
// There is no other way to get text-wrap and centered (req display: table-cell,
// not avail until IE8).
//
// Used only by Test.htm.  ASP uses <%=strPseudoTable%> and <%=strPseudoTd%> 
// 
$(function () {
	var badBrowser = $.browser.msie && /MSIE (5|6|7)/.test(navigator.userAgent);
	var newTds;
	if (badBrowser) {
		$('div.pseudo-td').wrap('<td class="pseudo-td jscript" />');
		//
		// BUG: The explicit attrib width="100%" is required.
		// css('width','100%') doesn't render correctly on IE7.
		//
		// <tbody> is also required because IE implicitly inserts it if missing.
		//
		// (jQuery uses dom.appendChild(x), not dom.innerHTML=x because
		// the latter is not allowed by IE for table or td.
		$('div.pseudo-table').wrap('<table width="100%" class="pseudo-table"><tbody><tr /></tbody></table>'); // tr is innermost element in the wrap
		newTds = $('td.pseudo-td.jscript');
		// Hoist vertical-align:x from <div> up to the enclosing <td>
		newTds.css('vertical-align', function (index, oldAttr) {
			return $($('>div', newTds)[index]).css('vertical-align');
		});
		// Hoist text-align:x from <div> up to the enclosing <td>
		newTds.css('text-align', function (index, oldAttr) {
			return $($('>div', newTds)[index]).css('text-align');
		});
		//
		// BUG: div.#foo-widecol { width: 90%; } is actually 90% of the
		// enclosing <td>, not the whole table.
		// 
		// WORKAROUND: Hoist 'width: 90%;' from the <div> to the enclosing <td>.
		// We do this upon seeing the magic sub-string "wide" inside of
		// <div id='fooWide' class='pseudo-td'> or
		// <div class='fooWide pseudo-td'>
		// 
		// BUG: The CSS value 'width: 90%;' is not stored anywhere
		// in the DOM!  Only the actual pixel value is stored in the DOM node
		// ('452px').  The only place that records '90%' is in original
		// implicitly-inherited CSS style object, and which one was applied
		// is unknown at runtime (AFAIK).
		// 
		// WORKAROUND: We assume any <div class='pseudo-td'> with 'wide' must
		// be the widest column in the table, so we apply <td width=90%>.
		//
		$('td.pseudo-td > div.pseudo-td').each(function (index) { // Loop over each div
			var id = $(this).attr('id');
			if (id && id.toLowerCase().indexOf('wide') >= 0) {
				// Found <div id="fooWideBaz">. Hoist up width: 90%.
				$(this).css('width', 'auto'); // delete
				$(this).parent().css('width', '90%'); // apply to parent <td>
			} else {
				if (this.className && this.className.toLowerCase().indexOf('wide') >= 0) {
					// Found <div class="pseudo-td fooWide">. Hoist wide-width
					$(this).css('width', 'auto'); // delete
					$(this).parent().css('width', '90%'); // apply to <td>
				}
			}
		});
	}
});
//
// Emulate min-width and max-width on IE6 for .content-container.
//
if (!oAlgin.minWidth) {
	oAlgin.minWidth = 480; // failsafe default
}
if (!oAlgin.maxWidth) {
	oAlgin.maxWidth = 900; // failsafe default
}
$(function () {
	if (($.browser.msie && $.browser.version.substr(0, 1) === '6')) { // if IE6
	/*
		var content = $('.content-container'), wid,
			rnumpx = /^[\d\.]+(?:px)?$/i; // '500px', '720.5px', '720.5'
		// Kludge: Pass min-width via _background-position-x
		wid = content.css('background-position-x');
		if (rnumpx.test(wid)) {
			wid = parseFloat(wid);
			if (wid) {
				content.css('background-position-x', '0px'); // must reset!
				oAlgin.minWidth = parseFloat(wid);
			}
		}
		// Kludge: Pass max-width via _background-position-y
		wid = content.css('background-position-y');
		if (rnumpx.test(wid)) {
			wid = parseFloat(wid);
			if (wid) {
				content.css('background-position-y', '0px'); // must reset!
				oAlgin.maxWidth = parseFloat(wid);
			}
		}
	*/
		$(window).resize(oAlgin.fixWidthForIE6); // Arrange call on resize event
		oAlgin.fixWidthForIE6(); // Ready event: Call immediately
	}
});
oAlgin.fixWidthForIE6 = function () {
	var widthWindow = $(window).width();
	if (!oAlgin.bResizingIE6) {
		//
		// minWidth and maxWidth are for the inner width of content-container.
		// It does not include the 3px border on each side (6px total) nor any
		// margin/padding of the enclosing body (currently 0).
		//
		// Increase from 6px to 14px for slop to avoid thrashing.
		//
		if (widthWindow < oAlgin.minWidth) {
			oAlgin.bResizingIE6 = true;
			oAlgin.bAdjustedIE6Width = true;
			$('.content-container').width(oAlgin.minWidth); // triggers re-entry
		} else if (widthWindow > oAlgin.maxWidth + 14) {
			oAlgin.bResizingIE6 = true;
			oAlgin.bAdjustedIE6Width = true;
			$('.content-container').width(oAlgin.maxWidth); // triggers re-entry
		} else if (oAlgin.bAdjustedIE6Width) { // if need to revert to auto
			oAlgin.bAdjustedIE6Width = false;
			$('.content-container').width('auto'); // triggers re-entry
		}
	} else { // ignore re-entry
		oAlgin.bResizingIE6 = false;
	}
};
//
// Detect FontSmoothing
//
oAlgin.hasFontSmoothing = function () {
	if (/Windows NT [345]/.test(navigator.userAgent)) { // if NT, W2K, or XP
		return false; // font-smoothing on XP is awful - dont use
	}
	// MSIE 4+ reports via screen.fontSmoothingEnabled
	if ((typeof screen.fontSmoothingEnabled) !== 'undefined') {
		return screen.fontSmoothingEnabled;  
	}
	// Non-IE (or non-Windows)
	try {
		var i, j;
		// Create a 35x35 Canvas block.
		var canvasNode = document.createElement("canvas");
		canvasNode.width = "35";
		canvasNode.height = "35";

		// We must put this node into the body, otherwise 
		// Safari Windows does not report correctly.
		canvasNode.style.display = "none";
		document.body.appendChild(canvasNode);
		var ctx = canvasNode.getContext("2d");
        
		// draw a black letter "O", 32px sans-serif.
		ctx.textBaseline = "top";
		ctx.font = "32px sans-serif";
		ctx.fillStyle = "black";
		ctx.strokeStyle = "black";
        
		ctx.fillText("O", 0, 0);
        
		// start at (8,1) and search the canvas from left to right,
		// top to bottom to see if we can find a non-black pixel.  If
		// so we return true.
		for (j = 8; j <= 32; j++) {
			for (i = 1; i <= 32; i++) {
				var imageData = ctx.getImageData(i, j, 1, 1).data;
				var alpha = imageData[3];
				if (alpha !== 255 && alpha !== 0 && alpha > 180) {
					return true; // font-smoothing must be on.
				}
			}
		}
		// didn't find any grayish pixels - return false.
		return false;
	} catch (ex) {
		// Something went wrong (for example, Opera cannot use the
		// canvas fillText() method.
		return false;
	}
};
//
// Add the following classes to the html tag:
//	"hasFontSmoothing" if font smoothing is enabled
//	"hasFontSmoothing-false" if font smoothing is disabled
//       
// Side effect: Load the Google fonts
// 
$(function () {
	var result = oAlgin.hasFontSmoothing();
	if (result) {

		$('html').addClass('hasFontSmoothing'); // Enable the fonts

		//
		// BUG: Google fonts cause a Flash Of Unstyled Text (FOUT).
		// 
		// WORKAROUND: To avoid FOUT, call the Google Webfont Loader
		// explicitly, and arrange to hide the content until the fonts
		// are loaded.  Afterwards fade in the resulting text.
		// See http://www.storiesinflight.com/html5/webfonts/index.html
		// 
		var badBrowser = $.browser.msie && /MSIE (5|6|7|8)/.test(navigator.userAgent);
		if (badBrowser) {
			//
			// BUG: Google WebFonts botches MSIE 5-8.  It delays for 2 seconds
			// then fires the 'inactive' (failed) callback.
			//
			// WORKAROUND: Don't use the WebFont loader on MSIE 5-8
			//
			oAlgin.onReadyAnimationDone();
		} else {
		  try {
			if (WebFont.load) { // http://ajax.googleapis.com/ajax/libs/webfont/1/webfont.js
				$('div.content-container').hide();
				//
				// Use the Google Webfont Loader (cool!)
				// http://code.google.com/apis/webfonts/docs/webfont_loader.html
				// 
				WebFont.load({ // Might throw (?)
					google: { // Fonts to load
						//families: [ 'Droid+Sans', 'Droid+Sans+Mono' ]
						families: [ 'Droid+Sans', 'Droid+Sans:bold' ]
					},
					loading: function() {
						// Can show animation while loading
					},
					active: function() {
						// BUG: Must wait for the restyling before fadeIn.
						// (Any short delay is sufficient on IE for repaint.
						// FireFox needs 200ms on 1st page load.)
						$('div.content-container').delay(200)
							.fadeIn(300, oAlgin.onReadyAnimationDone);
					},
					inactive: function() {
						// Font didn't load from Google - show text as-is	
						$('div.content-container').fadeIn(300, oAlgin.onReadyAnimationDone);
					}
				});
			}
		  } catch(e) { // Oops, WebFont object is missing or bad
			$('div.content-container').show();
			oAlgin.onReadyAnimationDone();
		  }
		}
	} else {
		$('html').addClass('hasFontSmoothing-false');
		oAlgin.onReadyAnimationDone();
	}
	//$('html').addClass('debug');  // Uncomment to enable layout-debugging
});
//}(jQuery)); // must be last

