// 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 sPath = window.location.pathname;

var sPage = sPath.substring(sPath.lastIndexOf('/') + 1);

var sPage = sPage.split(".");


var _heightTbl4Col=0;
var $timer = null;
function $more_over(){
	clearTimeout( $timer );
	$("#more .tbl-4col").animate({height:_heightTbl4Col},250);
};
function $more_out(){
	$timer=setTimeout('$more_out_timer()',100);
}
function $more_out_timer(){
	$("#more .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){

//************************************************************************************/
// FLV VIDEO PLAYER
/************************************************************************************/


if($('#videoName').length > 0){
     var e = $('#videoName').html();

		// hide from user. This will appear in SiteKit as javascript is not parsed.
		$('#videoName').css("display","none");

		// find value between hashes, i.e. #value#
		var firstDelimeter = e.indexOf("#") + 1;
		var lastDelimeter = e.lastIndexOf("#");

		// slice string inside delimeters
		e = e.slice(firstDelimeter,lastDelimeter)
		
		// only place the video if the video name is not blank
		if(e!=""){
			displayVideoPlayer(e.toLowerCase());
		}else{
			document.getElementById('video').style.display = "none";
		}
}

//************************************************************************************/
// END FLV VIDEO PLAYER
/************************************************************************************/

/* Style the search results submit button 'proper' */
if ($('#searchform .SubmitButtonelement').length > 0){
    $('.SubmitButtonelement').css({ 'width' : "140px"});
    $('.SubmitButtonelement').wrap('<span class="submit" />');
}



	// HIDE SEO TEXT DIV ON HOMEPAGE, AND LANDING PAGES IF THEY ARE NOT 
	// POPULATED
	
	// detect the presense of div id "seoText" on load
	
	if($("#seoText").length > 0){
		if($("#seoText").children().length == 0){ // no seo text entered			
			$("#seoText").parent().remove(); // take elements out of the DOM			
		}		
	}







	/*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();
	$('label.overlabel404').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 (){ $("#more .tbl-2col", $(this)).slideToggle("fast"); }, function (){ $("#more .tbl-2col", $(this)).slideToggle("fast"); });
	$("#more #clist").hover( function (){ $("#more .cselect", $(this)).slideToggle("fast"); }, function (){ $("#more .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;
				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; 
}

//Function to select current menu
SelectCurrentMenu = function(value)
{
  var _SelectedMenuId = "";

if(window.location.pathname!= "/")
  { 
  switch(parseInt(value))
  {
    case 1:
        _SelectedMenuId = "security";
        break; 
    case 2:
        _SelectedMenuId = "enterprise";
        break;
    case 3:
        _SelectedMenuId = "business";
        break;
    case 4:
        _SelectedMenuId = "government";
        break;
    default:
        _SelectedMenuId ="";
  }}
  
  if(_SelectedMenuId != "")
     $("#" + _SelectedMenuId).addClass("currSection");
}


//Function to get querystring value
function GetQueryStValue(key) 
{
    var Track_event = $("body").attr('id');
    var QueryString = window.location.search.substring(1);
    var arrQS = QueryString.split("&");
    
    if (Track_event != "")
    {
       return Track_event;
    }else
    {
    for (i=0; i<arrQS.length; i++)
    {
        var KeyValue = arrQS[i].split("=");
        if (KeyValue[0].toLowerCase() == key.toLowerCase()) 
        {
            //return "event"+KeyValue[1];
            return KeyValue[1];
        }
    }
   }
    return "";
}



//function  to url encode or decode
function URLEncode (clearString) {
  var output = '';
  var x = 0;
  clearString = clearString.toString();
  var regex = /(^[a-zA-Z0-9_.]*)/;
  while (x < clearString.length) {
    var match = regex.exec(clearString.substr(x));
    if (match != null && match.length > 1 && match[1] != '') {
    	output += match[1];
      x += match[1].length;
    } else {
      if (clearString[x] == ' ')
        output += '+';
      else {
        var charCode = clearString.charCodeAt(x);
        var hexVal = charCode.toString(16);
        output += '%' + ( hexVal.length < 2 ? '0' : '' ) + hexVal.toUpperCase();
      }
      x++;
    }
  }
  return output;
}

function URLDecode (encodedString) {
  var output = encodedString;
  var binVal, thisString;
  var myregexp = /(%[^%]{2})/;
  while ((match = myregexp.exec(output)) != null
             && match.length > 1
             && match[1] != '') {
    binVal = parseInt(match[1].substr(1),16);
    thisString = String.fromCharCode(binVal);
    output = output.replace(match[1], thisString);
  }
  return output;
}

//function to open url for promo banner
OpenUrl = function(url){
   var tempurl = url.toLowerCase();
   if(tempurl.indexOf('fireaudit') > -1 && tempurl.indexOf('http://') > -1)
       window.open(tempurl,"fireaudit","width=680,height=760,scrollbars=1");
   else if(tempurl.indexOf('http://') > -1)
       window.open(tempurl);
   else
       window.location.href = tempurl;
}

//IE Fix for the drop down
IE_DDFix = function(){
    if($.browser.msie)
    {
        $("select").each(function(i) {
            if(!($(this).hasClass("IEFix")))
            {
                var width=0;
                var width1=0;
                width = $(this).width();
                
                if(width > 0)
                {
                    $(this).css("width", "auto");
                    width1 = $(this).width(); //($(this).width() == 0 ? parseInt($(this).css("width")):$(this).width());

                    $(this).wrap('<div style="padding:0;margin:0;width:'+ (width + 2) +'px;overflow:hidden;" />');//.css("width")
                    $(this).css("width", width + "px").addClass("IEFix");
                    
                   if(width1 > width)
                   {
                       $("#" + $(this).attr('id')).mousedown(function(){
                            $(this).css("width", "auto");
                       })

                       $("#" + $(this).attr('id')).change(function(){
                            $(this).css("width", ($(this).parent().width()-2) + "px");
                       });

                       $("#" + $(this).attr('id')).blur(function(){
                            $(this).css("width", ($(this).parent().width()-2) + "px");  
                       });
                   }
                }
            }
        });
    }
}

//IE Fix for the drop down
$(window).load(function() {
  IE_DDFix();
});

	/************************************************************************************/
	// page name
	/************************************************************************************/
	
	var sPath = window.location.pathname;
	var sPage = sPath.substring(sPath.lastIndexOf('/') + 1);
	var sPage = sPage.split(".");
	
	/**
	 * A simple querystring parser.
	 * Example usage: var q = $.parseQuery(); q.foo returns "bar" if query contains "?foo=bar"; multiple values are added to an array. 
	 * Values are unescaped by default and plus signs replaced with spaces, or an alternate processing function can be passed in the params object .
	 *
	 **/

	jQuery.parseQuery = function(qs,options) {
		var q = (typeof qs === 'string'?qs:window.location.search), o = {'f':function(v){return unescape(v).replace(/\+/g,' ');}}, options = (typeof qs === 'object' && typeof options === 'undefined')?qs:options, o = jQuery.extend({}, o, options), params = {};
		jQuery.each(q.match(/^\??(.*)$/)[1].split('&'),function(i,p){
			p = p.split('=');
			p[1] = o.f(p[1]);
			params[p[0]] = params[p[0]]?((params[p[0]] instanceof Array)?(params[p[0]].push(p[1]),params[p[0]]):[params[p[0]],p[1]]):p[1];
		});
		return params;
	}
	


// display video in templates where required

function displayVideoPlayer(e){
		var flashvars = {flvLocation:e};
		var params = {wmode: "transparent"};
		var attributes = {};
		swfobject.embedSWF("http://www.adt.eu/common/swf/flv-player.swf", "flashcontent", "480", "307", "8.0.0", "http://www.adt.eu/common/swf/flv-player.swf", flashvars, params, attributes);

}


