// remap jQuery to $
(function($){

// jQuery Cookie JavaScript for MDT
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        var path = options.path ? '; path=' + options.path : '';
        var domain = options.domain ? '; domain=' + options.domain : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

})(this.jQuery);

/* Author:

*/

$(document).ready(function(){
	$("#qt").focus(function() {
		if( this.value == this.defaultValue ) {
			this.value = "";
		}
	}).blur(function() {
		if( !this.value.length ) {
			this.value = this.defaultValue;
		}
	});
	$("a[rel='contact-us-popup']").each(function(){
	
		var this_href = $(this).attr("href");
		var queryStringToken = "?";
		if(this_href.indexOf("?") > -1)
		{
			queryStringToken = "&";
		}
		var thickbox_href = "TB_iframe=true&height=520&width=375";
		$(this).attr('href', this_href + queryStringToken + thickbox_href);
	});
	
	$("a[rel='external']").mouseover(function(){
		var original_href = $(this).attr("href");
		var mdt_leaving_ext_href = $("#leaving-site").attr("href");
		var thickbox_href = mdt_leaving_ext_href + "?TB_iframe=true&height=320&width=460";
		$.cookie('urlCookie', original_href, { path: '/' });
		$(this).attr('href', thickbox_href);
	}).mouseout(function(){
		var myCookie = $.cookie('urlCookie');
		$(this).attr('href', myCookie);
	});
	
	$("a[rel='send-to-friend-popup']").each(function(){

		var this_href = $(this).attr("href");
		var queryStringToken = "?";
		if(this_href.indexOf("?") > -1)
		{
			queryStringToken = "&";
		}
		var thickbox_href = "TB_iframe=true&height=650&width=375";
		$(this).attr('href', this_href + queryStringToken + thickbox_href);
	});
	
	/*begin external link popup*/
	$("a.extUrl").attr({href: $.cookie('urlCookie'),innerHTML: $.cookie('urlCookie')});
				
	$("#closeDialog").click(function(){
		self.parent.tb_remove();
	});
	
	$("p.toggler").click(function(){
		$(this).next().slideToggle("slow");
	});
	
	$("a[class*='video']").each(function(){

		var this_href = $(this).attr("href");
		//var dDocName = $(this).attr("rel");
		
		var queryStringToken = "?";
		if(this_href.indexOf("?") > -1)
		{
			queryStringToken = "&";
		}
		
		var width;
		var height;
		if($(this).hasClass('480x360'))
		{
			width = "480";
			height = "415";
		}
		else if ($(this).hasClass('480x270'))
		{
			width = "470";
			height = "295";
		}
		else
		{
			width = "480";
			height = "400";
		}
		var contentId = getHrefQueryStringParameter(this_href,'contentid');

		var thickbox_href = "TB_iframe=true" + "&height=" + height + "&width=" + width + "&contentid=" + contentId;
		$(this).attr('href', this_href + queryStringToken + thickbox_href);
	});
    
    
    
});

// begin region re-location
$(window).load(function() {
	var rms = $('div.wcm-region-marker');
	if (rms.length > 0) { 
    	rms.each(function(index){
        	$(this).attr('style', 'left:0px; top:' + (index+1) * 30 + 'px');
    	});
	}
});
// end region re-location

/***************************************/
/*begin popup code*/
/***************************************/
	/*begin general use popup*/
	$("a.popup").click(function() {
		//get data from clicked anchor
		var puUrl = $(this).attr('href');
		var puTitle = $(this).attr('title');
		var puWidth = $(this).attr('width');
		if(puWidth != '')
		{
			puWidth = parseFloat(puWidth);
		}
		var puHeight = $(this).attr('height');
		if(puHeight != '')
		{
			puHeight = parseFloat(puHeight);
		}
		var containerDiv = $(document.createElement('div'));
		$(containerDiv).attr("id","video-popup");
		
		$.ajax({
  			url: puUrl,
  			async: false,
  			success: function(data) {
    			$(containerDiv).append(data);
    			
    			showPopup(containerDiv,puTitle,{width:puWidth,height:puHeight,draggable:false,resizable:false});
  			}
		});
		//showPopup(containerDiv,puTitle,{width:puWidth,height:puHeight,draggable:false,resizable:false});
		return false;
	});
	/*end general use popup*/
	
	/*begin view larger popup code*/
	$("a.view-larger-img,a.magnify").click(function() {
		//get data from clicked anchor
		var imgUrl = $(this).attr('href');
		var imgCaption = $(this).attr('title');
		var imgAlt = $(this).attr('title');
		var imgHeight = parseFloat($(this).attr('height'));
		var imgWidth = parseFloat($(this).attr('width'))+30;
		//create an inital html object as a container
		var containerDiv = $(document.createElement('div'));
		$(containerDiv).attr("id","view-larger-img");
		//create image object and add attributes
		var img = new Image();
		img.src = imgUrl;
		img.alt = imgAlt;
		//add the elements to the container
		containerDiv.append(img);
		//showPopup(containerDiv,imgAlt,{height:imgHeight,width:imgWidth,resizable:false});
		showPopup(containerDiv,imgCaption,{width:imgWidth,resizable:false});
		return false;
	});
	
	$('.ui-widget-overlay').live("click", function() {
    	//Close the dialog
    	$("#view-larger-img").dialog("close");
	});
	/*end view larger popup code*/
	
	
	
	$('.ui-widget-overlay').live("click", function() {
    	//Close the dialog
    	$("#video-popup, #thickbox-popup").dialog("close");
	});
	
	function showPopup(html,popupTitle,options)
	{
		if(options != undefined)
		{
			var pCloseOnEscape=getDialogOption(options.closeOnEscape, true);
			var pHeight=getDialogOption(options.height, 'auto');
			var pOpen = getDialogOption(options.open, 'auto');
			var pWidth=getDialogOption(options.width, 'auto');
			var pDialogClass=getDialogOption(options.dialogClass, '');
			var pDraggable=getDialogOption(options.draggable, true);
			var pResizable=getDialogOption(options.resizable, true);
		}
		var $dialog = $(html)
		.dialog({
			autoOpen: false,
			closeOnEscape: pCloseOnEscape,
			dialogClass: pDialogClass,
			draggable: pDraggable,
			height: pHeight,
			modal: true,
			resizable: pResizable,
			title: popupTitle,
			width: pWidth
			
		});
		
		$dialog.dialog('open');
		if(options != undefined)
		{
			if(options.hideCloseButton)
			{
				$("a.ui-dialog-titlebar-close").css('display','none');
			}
		}
		
		return false;
	}
	
	function getDialogOption(value, defaultValue)
	{
		var returnValue;
		if((value === '')||(value === undefined))
		{
			returnValue = defaultValue;
		}
		else
		{
			returnValue = value;
		}
		
		return returnValue;
	}
/***************************************/
/*end popup code*/
/***************************************/

function getHrefQueryStringParameter(href,paramName)
{
	var hrefParams = href.substring(href.indexOf("?")+1);
	var params = hrefParams.split("&");
	var paramValue = undefined;
    for (i=0;i<params.length;i++) 
    {
        param = params[i].split("=");
        if (param[0] == paramName)
        {
            paramValue = param[1];
        }
    }
	return paramValue
}

/* ROTATING LOGOS */
jQuery(document).ready(function(){	
	showing = jQuery('#rotating_items div.rotating_item:first'); // Initiate the 'showing' variable as the first rotating_item
	showing.siblings('div').hide(); // Hide all other rotating_items
	setInterval("show_next_rotating_item(showing)", 5000); // Set the rotate time to 5 seconds
});
 
// Below is the code that picks an item at random to display
jQuery.jQueryRandom = 0;  
jQuery.extend(jQuery.expr[":"],  
{  
    random: function(a, i, m, r) {  
        if (i == 0) {  
            jQuery.jQueryRandom = Math.floor(Math.random() * r.length);  
        };  
        return i == jQuery.jQueryRandom;  
    }  
}); 
 
// The below function repeatedly gets called, to do the rotating
function show_next_rotating_item(t){
	jQuery(t).fadeOut('slow');
 
	var next_rotating_item = jQuery(t).siblings('.rotating_item:random');
	if(!next_rotating_item.attr('class')){
		next_rotating_item = jQuery('#rotating_items div.rotating_item:first');
	}
	next_rotating_item.fadeIn('slow');
	showing = next_rotating_item;	
}


/* IMAGE ROLLOVER */
function preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.p) d.p=new Array();
    var i,j=d.p.length,a=preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.p[j]=new Image; d.p[j++].src=a[i];}}
}

function swapImgRestore() { //v3.0
  var i,x,a=document.sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function swapImage() { //v3.0
  var i,j=0,x,a=swapImage.arguments; document.sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=findObj(a[i]))!=null){document.sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}


/* SHARE SLIDER */
$(document).ready(function(){
	//Fix Errors - http://www.learningjquery.com/2009/01/quick-tip-prevent-animation-queue-buildup/
	
	//Remove outline from links
	$("a").click(function(){
		$(this).blur();
	});
	
	//When mouse rolls over
	$(".share li").mouseover(function(){
		$(this).stop().animate({height:'220px'},{queue:false, duration:200, easing: 'easeOutSine'})
	});
	
	//When mouse is removed
	$(".share li").mouseout(function(){
		$(this).stop().animate({height:'25px'},{queue:false, duration:200, easing: 'easeOutSine'})
	});	
});

var maxcolHeight = 0;
/* Brian 6-9-11 New equals heights */
/*$(".box").equalHeights();*/

/*  Old equal heights*/

var maxboxHeight = 0;
$("#home-content-welcome, #home-content-featured, #home-content-stories").each(function(){
	if ($(this).height() > maxboxHeight) { maxboxHeight = $(this).height(); }
});
$("#home-content-welcome, #home-content-featured, #home-content-stories").height(maxboxHeight);


/* Begin Rotating Banner Script */
var rotatorObject;	
function rotateHPBannerImages() {
    //var oCurPhoto = $('#rotating-banner img.current');
    var oCurPhoto = $('#rotating-banner').children(".current")
    var oNxtPhoto = oCurPhoto.next();
    
    if (oNxtPhoto.length == 0) {
        //oNxtPhoto = $('#rotating-banner img:first');
        oNxtPhoto = $('#rotating-banner').children(":first");
    }

    oCurPhoto.removeClass('current').addClass('previous');
    
    oNxtPhoto.css({ opacity: 0.0 }).addClass('current').animate({ opacity: 1.0 }, 1000,
        function() {
            oCurPhoto.removeClass('previous');
        });
    
    //get the indicator that is currently "on"
    var curIndicator = $('#slide-indicator li.indicator-on');
    
	//get the next indicator
    var nextIndicator = curIndicator.next();
    
    //if there is not another indicator after the current
    //start over at the begining of the collection
    if (nextIndicator.length == 0) {
        nextIndicator = $('#slide-indicator li:first');
    }
    //remove the "on" class and add the "off" class
    curIndicator.removeClass('indicator-on').addClass('indicator-off');
    
    //add fade effect with animate to fade in the new one and after
    //the fade is complete remove the class
    nextIndicator.css({ opacity: 0.0 }).addClass('indicator-on').animate({ opacity: 1.0 }, 250,
        function() {
            curIndicator.removeClass('indicator-off');
        });
}

function goToBannerImage(imgIndex) {
	//stops the rotation.
	clearInterval(rotatorObject);
	
	$(".hp-image-container").each(function(index) {
		if(index == imgIndex) {
			$(this).addClass('current');
			$(this).removeClass('previous');
		}
		else {
			$(this).removeClass('current previous');
		}
	});
	
	$("#slide-indicator li").each(function(index) {
		if(index == imgIndex) {
			$(this).addClass('indicator-on');
			$(this).removeClass('indicator-off');
		}
		else {
			$(this).removeClass('indicator-on indicator-off');
		}
	});
}

function setIntervalObject(obj) { rotatorObject = obj; }
/* End Rotating Banner Script */
