// JavaScript Document
//http://www.alistapart.com/articles/makingcompactformsmoreaccessible

// firebug degradiation
if (! ("console" in window) || !("firebug" in console)) {
    var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml", "group"
                 , "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];
    window.console = {};
    for (var i = 0; i <names.length; ++i) window.console[names[i]] = function() {};
}

// utility functions 
function endBubble(evt)
{
    if(evt.cancelBubble == false){ 
        evt.cancelBubble = true; 
        evt.returnValue = false;
        
     }
	 if (evt.stopPropagation) {
	    evt.stopPropagation(); 
	    evt.preventDefault();
    	
	 }
}

/**
 * This function allows the programmer to retrieve objects biased on the class name you 
 * want to retrieve. Similar to the GetElementByID and GetElementByTagName.
 * @member UtilNS
 * @param {object} oElm The object you want to search, could be a whole document or something more specific.
 * @param {string} strTagName The string containing the name of the tag name i.e. "a", "div", "span" what ever the class name is attached to.
 * If no tag is given it will search all elements.
 * @param {string} strClassName The string containing the class name you're searching for
 * @returns An array filled with the class names found in the search
 * @type Array
 * {@link  http://www.robertnyman.com/2005/11/07/the-ultimate-getelementsbyclassname/#more-256 getElementsByClassName} Utility Function
 */


function getElementsByClassName(oElm, strTagName, strClassName){
	var arrElements = (strTagName == "*" && document.all)? document.all : oElm.getElementsByTagName(strTagName);
	var arrReturnElements = new Array();
	strClassName = strClassName.replace(/\-/g, "\\-");
	var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
	var oElement;
	for(var i=0; i<arrElements.length; i++){
		oElement = arrElements[i];		
		if(oRegExp.test(oElement.className)){
			arrReturnElements.push(oElement);
		}	
	}
	return arrReturnElements;
}

function addEvent(_target,_event,_function){
	if (_target.addEventListener)
		_target.addEventListener(_event, _function, false );
	else{
		_target.attachEvent('on'+_event, _function);
		ieModel = true;	
	}	
}

var _heightTbl4Col=0;
var $timer = null;
function $more_over(){
	clearTimeout( $timer );
	$(".tbl-4col").animate({height:_heightTbl4Col},250);
};
function $more_out(){
	$timer=setTimeout('$more_out_timer()',100);
}
function $more_out_timer(){
	$(".tbl-4col").animate({height:0},150,function(){$(this).css('display','none');});
};
function WireAutoTab(CurrentElementID, NextElementID, FieldLength) {
		//Get a reference to the two elements in the tab sequence.
		var CurrentElement = $('#' + CurrentElementID);
		var NextElement = $('#' + NextElementID);

		
		CurrentElement.keyup(function(e) {
		//Retrieve which key was pressed.
		var KeyID = (window.event) ? event.keyCode : e.keyCode;
		
		//If the user has filled the textbox to the given length and
		//the user just pressed a number or letter, then move the
		//cursor to the next element in the tab sequence.   
		if (CurrentElement.val().length >= FieldLength
			&& ((KeyID >= 48 && KeyID <= 90) ||
			(KeyID >= 96 && KeyID <= 105)))
			NextElement.focus();
		});
}
		
$(document).ready(function(event){
	/*BEGIN AUTOTAB FORMS */						   
	 WireAutoTab('wucIntForms_txtphone1', 'wucIntForms_txtphone2', 3);
     WireAutoTab('wucIntForms_txtphone2','wucIntForms_txtphone3', 3);
		
		
	/*END AUTOTAB FORMS */						   
	
	$('img[src$=.png]').fixpng();
	$("#site-info li:last-child, #nav-top li:last-child, #nav-search li:last-child, .tbl-row > div:last-child, .graySolidBox div:last-child," +
	  "#nav-sub li:last-child, #banner li:last-child, li:last-child").addClass("last-child");
	$("#nav-top li:first-child, .graySolidBox div:first-child, .tbl-row > div:first-child, #banner li:first-child, li:first-child").addClass("first-child");
	
	$('#nav-top li').mouseover(function(){
		if ( !( $(this).hasClass("first-child") || $(this).hasClass("last-child") )) {
			$(this).addClass("hover");
		}
    }).mouseout(function(){
      $(this).removeClass("hover");	
    });

	$('label.overlabel').overlabel();
	
	$("#content-main .blueBoundBox").equalizeCols();
	$(".grayShade .tbl-col > div, .tbl-3col + .teachingBox .tbl-col").equalizeCols();
	$(".teachingBox + .teachingBox .tbl-col").equalizeCols();
	$(".tbl-3col .teachingBox").equalizeCols();
	$('#landing .boxes-wseparator .tbl-col .box-body').equalizeCols();
	$('.blue-box-home').equalizeCols();
	$('.eq').equalizeCols();
	$('.equalize').equalizeCols();
	$('.equalize2').equalizeCols();
	
	$(".teachingBox .imgHolderSmall").each ( function () { 
		var height = $(this).parent().height();
		$(this).css("height", height);
	});
	
	$(".blueBoundBox .more-link, .grayShade .more-link").css({"position": "absolute", "width": "270px", "bottom": "10px"});
	$(".grayShade .more-link").css("bottom", 0);
	
	$(".tabbedPane ul").each( function() { 
		var totalWidth = $(this).width();
		var $aTags = $("a", $(this));
		var aTagsWidth = Math.floor((totalWidth - (20*$aTags.length + 2*$aTags.length-1))/$aTags.length);

		$aTags.each( function (a) {
			$(this).width( (a == $aTags.length-1) ? aTagsWidth+1 :aTagsWidth);
		});
	});
	
	
	_heightTbl4Col = $("#more .tbl-4col").height();
	$("#more").hover($more_over,$more_out);
	$("#more .tbl-4col").css('height','0px');
	/*
	var _heightTbl4Col = 0;
	var _visibleTbl4Col = false;
	var tmp = $(".tbl-4col").height()
	if(tmp>_heightTbl4Col){ _heightTbl4Col = tmp; }
	$("#more").hover( function (){
					if(_visibleTbl4Col==false){
						$("#more .tbl-4col").css('height','0px');
						$("#more .tbl-4col").animate({height:_heightTbl4Col},400,function(){_visibleTbl4Col=true;});
					}
				}, function (){ 
					if(_visibleTbl4Col==true){
						$("#more .tbl-4col").animate({height:0},100,function(){_visibleTbl4Col=false;}); 
					}
				});
	*/
	$("#more").hover( function (){ $(".tbl-2col", $(this)).slideToggle("fast"); }, function (){ $(".tbl-2col", $(this)).slideToggle("fast"); });
	$("#clist").hover( function (){ $(".cselect", $(this)).slideToggle("fast"); }, function (){ $(".cselect", $(this)).slideToggle("fast"); });

	var url = location.href;
	$(".cselect a").each( function(){
		var className = $(this).attr("class");
		var newUrl = new String(url);
		$(this).attr("href", newUrl.replace(/(\/)([a-z]{2})(\/)/i,"/"+className+"/"));
		var site = newUrl.match(/(\/)([a-z]{2})(\/)/i);
		//console.debug("o", site);
		
		if(site!=null && $(this).hasClass(site[2].toLowerCase())) {
			$("#clist > a").text($(this).text());
			$(this).parent().remove();
		
		}
	});
	
	/*
	$("#home-form .submit").toggle (
		function () {
			$(this).css({"margin-top": "1px", "margin-right": "-1px"});	
		},
		function () {
			$(this).css({"margin-top": "0", "margin-right": "0"});	
		}
	);
	*/
	
	if ( $.browser.mozilla) {
 	  //console.debug(" %s", $("#nav-top > ul").css("overflow"));
	  $("#nav-top > ul").css("overflow", "visible");
	}
	
/*
	//$(".sub-1").addClass("last-child");
	$("#sub1").click(function () {
			$(".sub-1").removeClass("hide");
			//$(".sub-1").addClass("last-child");
			$(".sub-2").addClass("hide");
			$(".sub-3").addClass("hide");
	});
	$("#sub2").click(function () {
			$(".sub-1").addClass("hide");
			//$(".sub-2").addClass("last-child");
			$(".sub-2").removeClass("hide");
			$(".sub-3").addClass("hide");
	});
	$("#sub3").click(function () {
			$(".sub-1").addClass("hide");
			$(".sub-2").addClass("hide");
			//$(".sub-3").addClass("last-child");
			$(".sub-3").removeClass("hide");
	});
*/

	/*Accordion Control*/
	$('div.adtglobal-map').each(function(){
		var _jc = $(this);
		_jc.find('>map>area').click(function(){
			var _href = $(this).attr('href');
			_jc.find(_href).find('a.title').trigger('click');
			return false;
		});
		_jc.find('>ul.accordion-map>li').each(function(){
			var _jc_item = $(this);
			_jc_item.find('>div.item-container>a.title').click(function(){
				var _jci_a = $(this);
				var _jci_desc = _jci_a.parent().find('>div.desc');
				if( _jci_desc.is(':hidden') ){
					_jc.find('>ul.accordion-map>li div.desc:visible').slideUp(400,function(){
						_jc.find('>ul.accordion-map>li').removeClass('expand');
						_jci_desc.slideDown(600,function(){
							_jc_item.addClass('expand');
						});
					});
				}
				return false;
			});
		});
	});
});


/* =jQuery Plugins*/
(function($) {
	/* = plug-in : overlabel */
	$.fn.overlabel = function(options){
		var opts = $.extend( {},$.fn.overlabel.defaults, options );
		var selection = this.filter('label[for]').map(function(){
				var label = $(this);
				var id = label.attr('for');
				var field = $('#'+id);
				if(!field) return;http://adt.bgtpartners.com/global/v2/0-0-00-0.html
				var o = $.meta ? $.extend( {}, opts, label.data() ) : opts;
				label.addClass(o.label_class);
				var hide_label = function(){ label.css(o.hide_css) };
				var show_label = function(){ this.value || label.css(o.show_css) };
				$(field)
					.parent().addClass(o.wrapper_class).end()
					.focus(hide_label).blur(show_label).each(hide_label).each(show_label);
				return this;
		});
		return opts.filter ? selection : selection.end();
	};
	$.fn.overlabel.defaults = {
		label_class: 'overlabel-apply',
		wrapper_class: 'overlabel-wrapper',
		hide_css: { 'display': 'none' },
		show_css: { 'display': 'block' },
		filter: false
	};

	$.fn.equalizeCols = function() {
        var height = 0,
			reset = $.browser.msie ? "1%" : "auto";

        return this
			.css("height", reset)
			.each(function() {
			    height = Math.max(height, $(this).outerHeight(true));
			})
			.css("height", height)
			.each(function() {
			    var h = $(this).outerHeight(true);
			    if (h > height) {
			        $(this).css("height", height - (h - height));
			    };
			});

    };
	/* =plug-in : fix-png */
	$.fn.fixpng = function(){
		var hack = {
			isOldIE: $.browser.msie && $.browser.version < 7,
			filter: function(src){ return "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod='scale',src='"+src+"');"; }
		};
		return this.each(function(){
			if(hack.isOldIE){
				var $$=$(this);
				if($$.attr('src')){
					var span = document.createElement('span');
					$(span).attr({
						id: $$.attr('id'), className: $$.attr('class')
					});
					$(span).css({
						display: 'inline-block', width: $$.width(), height: $$.height(), filter: hack.filter($$.attr('src')), float: $$.attr('align')=='left'?'left':($$.attr('align')=='right'?'right':'none')
					});
					this.outerHTML = span.outerHTML;
				}
			}
		});
	};
	/*fill height to container**/
    $.fn.fill_height = function() {
        return this.each(function() {
			//console.debug("%s", $(this).attr("class"));
            var maxHeight = $(this).height();
            var sumChildrenHeights = 0;
            var children = $(this).children().not('.corner');
			//console.debug("%o %d", children, children.length);
            for(var i = 0, len = children.length; i < len; i++) {
                sumChildrenHeights = sumChildrenHeights + $(children[i]).outerHeight(true);
            }
			 
            var $lastchild = $(children[children.length - 1]);
			if($lastchild) {
            //console.debug("%o childHeight %d",$lastchild, sumChildrenHeights);
			$lastchild.height( ($lastchild.height() + (maxHeight - sumChildrenHeights)));
			}
        });
    };
	
})(jQuery);

//Print Function
function doPrint(){
        window.print();
}

//Email Script
function doEmail(subjbit,bodbit){
	email_str = "mailto:?subject="+subjbit+"&body=" + bodbit;
	email_str +=  " " + location.href;
	location.href = email_str;

}
