
/* {{{ error404 */
var error404 = function() {
	$("#error .text").click(function(){
		$(this).css('color', '#000');
		$(this).val("");
	});
};
/* }}} */

/* {{{ dropdowns */
var dropdowns = function() {
	$(".navList li").hover(function(){
		$(this).find('.navDropdown').css('display','block');
	}, function(){
		$(this).find('.navDropdown').css('display','none');
	});
};
/* }}} */
	
/* {{{ add n bg divs - jq plugin - dtw 20090416 */
var addBackgrounds = function() {
	$.fn.addBg = function(path,n,innerStyle) {	
		var loc = {
			'_l' :  'left repeat-y',
			'_r' :  'right repeat-y',
			'_t' :  'top repeat-x',
			'_b' :  'bottom repeat-x',
			'_tl' : 'left top no-repeat',
			'_tr' : 'right top no-repeat',
			'_br' : 'right bottom no-repeat',
			'_bl' : 'left bottom no-repeat'
		};

		var img = path.split('.');
	
		$(this).wrap('<div></div>').parent().addClass($(this).attr('class'))
			.css({'padding':'0px','border':'none'});
		
		var i = 1;
		for (suffix in loc) {
			// allow for n number of nested divs, corners first
			if (i > 8-n) {
				$(this).removeClass().css({'backgroundColor':'transparent'}).css(innerStyle)
				.wrap('<div class="bgLayer pos' + suffix + '"></div>').parent()
				.css({'background':'url(' + img[0] + suffix + '.' + img[1] + ') ' + loc[suffix]});
			}
			i++;
		}
	};
	
	$('.specialBoxOut').addBg('/apps/images/layout/common/box_out.png',8,{'padding':'16px'});
	$('.specialBoxIn').addBg('/apps/images/layout/common/box_in.png',8,{'padding':'16px'});
	$('.quoteBubble').addBg('/apps/images/layout/common/quote.png',4,{'padding':'14px 20px 14px 40px'});

	// apply ie6 transparent PNG fix after adding potentially transparent bgs
	if (typeof(DD_belatedPNG) !== 'undefined') {
		DD_belatedPNG.fix('.bgLayer');
	}
};
/* }}} */

/* {{{ site search */

$(document).ready(function() {
    // EE makes my code hurt
    var search = 'Search';
    // TODO: clean up
    $('form').each(function() {
        if ($(this).attr('id') == 'searchForm') {
            $($(this).children()[0]).children().each( function() {
                if ($(this).attr('name') == 'keywords') {
                    $(this).focus(function(){
                        if ($(this).val() == search) {
                            $(this).val('').css({'color':'#000'});
                        }
                    }).blur(function(){
                        if ($(this).val() == '' || $(this).val() == search) {
                            $(this).val(search).css({'color':'#999'});
                        }
                    }).blur();
                }
            });
            $(this).submit( function() {
                var result = true;
                $($(this).children()[0]).children().each( function() {
                    if ($(this).attr('name') == 'keywords') {
                        var q = $.trim($(this).val());
                        if (q == 'Search' || q == '') {
                            result = false;
                        }
                    }
                });
                return result;
            });  
        }
    });
});
/* }}} */

/* {{{ tooltipMouseover */
var tooltipMouseover = function() {
	var fade_time = 300;
	var hover_time = 300;

	$('.detailLink').mouseover(function(){
		// set location variables to check later on mouseleave
		detailpopup_hover = false;
		detaillink_hover = true;
	
		// find associated popup by id with suffix converted from Link to Popup
		popupId = $(this).attr('id').replace('Link','Popup');
		var $popup = $('#'+popupId)
			.prepend($(this).filter('.detailCaret').length < 1 ? '<div class="detailCaret"></div>' : '');

		// get position and dimensions of link and popup
		var position = $(this).position();
		var x = position.left;
		var y = position.top;
		var h_link = $(this).outerHeight();
		var w_link = $(this).outerWidth();
		var w_popup = $popup.outerWidth();

		// set relative position of popup
		if ($(this).hasClass('popupBelow')) {
			x = x + (w_link / 2) - (w_popup / 2);
			y = y + h_link + 8;
			$popup.addClass('popupBelow');
			
			//position caret halfway across popup
			$('.detailCaret').css({'left':w_popup/2 - 8});
		} else {
			// popupup left (default)
			x = x + w_link + 10;
			y = y - (h_link / 2) - 6;
		}
	
		// display popup at same position after hover
		setTimeout(function(){
			if (detaillink_hover) {
				// hide other popups
				$('.detailPopup').fadeOut(fade_time);
				// show intended popup
				$popup.css({'left':x,'top':y}).fadeIn(fade_time);
			}
		},hover_time);

		// fallback click anywhere incase it hangs
		$('body').click(function(){
			$popup.fadeOut(fade_time);
		});
	}).mouseleave(function(){
		// set location variable for reference in other event handlers
		detaillink_hover = false;

		// fade out popup if the mouse is not on the popup or link
		setTimeout(function(){
			if (!detailpopup_hover && !detaillink_hover) {
				$('.detailPopup').fadeOut(fade_time);
			}
		},hover_time);
	});

	$('.detailPopup').mouseover(function(){
		// set location variables to check later on mouseleave
		detailpopup_hover = true;
		detaillink_hover = false;
	}).mouseleave(function(){
		// set location variable for reference in other event handlers
		detailpopup_hover = false;

		// fade out popup if the mouse is not on the popup or link
		setTimeout(function(){
			if (!detaillink_hover && !detailpopup_hover) {
				$('.detailPopup').fadeOut(fade_time);
			}
		},hover_time);
	});
};
/* }}} */
	
/* {{{ Omniture Onclick Events */

// send additional page hit on login button click so logins will not register as bounces
var omnitureLoginBounceFilter = function() {
	$('#login').click(function() {
		s = s_gi(CFG_OMNITURE_SUITE);
		s.manageVars("clearVars");
		s.pageName="apps login";
		s.t();
	});
}

// send tracking var on chat link click, called along with chat popup function by 
// inline onclick event as set in cms-administrated global variable "chat_link"
var omnitureChatLinkClick = function() {
	$('.content [onClick*=promptChat()]').click(function() {
		var chat_names = {1:'Huey',2:'Dave',3:'Ian',4:'Kirk',5:'Melissa',6:'Taizoon',7:'Waldon',8:'Hartsock'}
		var chat_img_num = $(this).parents('.questions').css('background-image');
		var chat_context = chat_img_num ? chat_names[chat_img_num.slice(-7,-6)] : 'inline text link';

		s = s_gi(CFG_OMNITURE_SUITE);
		s.events = 'event14'; 		// chat link click
		s.eVar12 = chat_context; 	// name of person in chat link or inline text
		s.t();
	});
}

// send tracking var on support link click
var omnitureSupportLinkClick = function() {
	$('div.support a.button').click(function(){	
		s = s_gi(CFG_OMNITURE_SUITE);
		s.events = 'event7';				// support link click
		s.eVar5 = 'clicked support button';	// type of support request
		s.t();
	});
}

// send tracking var for calculator click
var omnitureSupportToolClick = function() {
	$('#calculator .handle').click(function(){
		s = s_gi(CFG_OMNITURE_SUITE);
		s.prop5 = 'exchange hybrid calculator';	// hybrid calulator click
		s.t();
	});

	$('.hosted_vs_in-house_exchange #form, .hosted_vs_in-house_exchange .pricing').click(function(){
		s = s_gi(CFG_OMNITURE_SUITE);
		s.prop5 = 'in-house vs hosted calculator';
		s.t();
	});
}

// send tracking var on partner referal link click
var omnitureReferralLinkClick = function() {
	$('a.external').click(function(){
		var ext_href = $(this).attr('href');

		s = s_gi(CFG_OMNITURE_SUITE);
		s.events = 'event10';	// partner link click
		s.eVar7 = ext_href;		// partner link url
		s.t();
	});
}

// send tracking var on signup button click
var omnitureSignupButtonClick = function() {
	$('.signupArea .button').click(function(){
		s = s_gi(CFG_OMNITURE_SUITE);
		s.events = 'event11';	// signup button click in header
		s.t();
	});
	$('.supportNav .signup .button').click(function(){
		s = s_gi(CFG_OMNITURE_SUITE);
		s.events = 'event12';	// signup button click in content
		s.t();
	});
}

// send unique tracking var for clicking each item in toolbar footer
var omnitureFooterToolbarClick = function() {
	$('#toolbar a').click(function(){
		s = s_gi(CFG_OMNITURE_SUITE);
		s.events = 'event19';				// footer toolbar item click
		s.eVar14 = $(this).attr('name');	// footer toolbar item name
		s.t();
	});
}

// send unique tracking var for clicking video thumbnail or associated link in sidebar
var omnitureSidebarVideoClick = function() {
	$video = $('#content-sub .video a');
	$video.click(function(){
		video_url = $video.find('img').attr('src');
		video_url = video_url.substr(video_url.lastIndexOf('/')+1);

		s = s_gi(CFG_OMNITURE_SUITE);
		s.events = 'event21';	// video sidebar image or link click
		s.eVar15 = video_url;	// video sidebar image name
		s.t();
	});
}
/* }}} */ 

/* {{{ markupPrep */
var markupPrep = function() {
	var listPrep = function() {
		$('> li:last', 'ul, ol').addClass('last');
	};
	
	var tablePrep = function() {
		$('table tr:odd').addClass('alt');
		$('table td:last, table th:last').addClass('last');
	};
	
	listPrep();
	tablePrep();
};
/* }}} */

/* {{{ blog_archiveFold
 * Toggles the +/- and the visiblity of the months and years under the year of the blog archive.
 * Also hides any year beyond the first.
 */
var blog_archiveFold = function() {
	if ($('body.blog').size() >	0) {
		$('#archives ul li > span').click(function(event) {
			event.preventDefault();
			$(this).parent().toggleClass('collapsed');
			$(this).siblings('ul').slideToggle('normal');
		});
		
		$('#archives > ul > li:gt(0)').addClass('collapsed').children('ul').hide();
	};
};
/* }}} */

/* {{{ Animate stats widget */

var animateStats = function() {
	var $list = $('#stats .majorList.animateList');

	if ($list.length) {	
		$list.cycle({
			fx: 'fade',
			speed: 500,
			timeout: 5000,
			next: '.number:not(#inanimateList .number)' /* click item to advance */
		});
	}

	var $list = $('.jquery-cycle');

	if ($list.length) {
		$list.cycle({
			fx: 'fade',
			speed: 500,
			timeout: 5000
		});	
	}
};

/* }}} */

/* {{{ Animate rotating banners */
var headerImages = function() {
	if ($('#feature-items li').size() > 0) {
		$('#feature-items').innerFade({
			indexContainer: '#feature-nav',
			speed: 1000,
			timeout: 10000
		});
	};
};
/* }}} */

/* {{{ Animate Careers images */
var startCareersImageFade = function() {
	if ($('#careersImageFade p').size() > 0) {
		$('#careersImageFade').innerFade({
			speed: 'slow',
			timeout: 5000,
			containerHeight: 252,
			type: 'sequence'
		});
	};
};
/* }}} */

/* {{{ htmlButtons - make it so that when you click on a div, it links to the first anchor contained within */

var htmlButtons = function() {
	var buttons = $('.htmlButton');
	if (buttons.length > 0) {
		for (var i=0; i<buttons.length; i++) {
			$('a', buttons[i])[0].onclick = function() { return(false); };
			buttons[i].onclick = function() { document.location.href = $('a', $(this))[0].href; };
		}	 
	}
	buttons = null;
};

/* }}} */

/* {{{ tabSets - Sets of divs with the class tabSet, a common "tabSet" attribute, and unique "name" attributes are made to behave like tabs.
                 Each tab should contain one or more elements with a class of "tabLink" and tabSet and target attributes.
                 The individual divs should each include the actual tabs, with the appropriate one selected.
                 tabSets should also be initially displayed correctly hidden and visible */

var tabSetOnClick = function()
{
	var tabSetName = this.getAttribute('tabSet');
	var targetName = this.getAttribute('target');
	var tabs = $('.tabSet');
	for (var i=0; i<tabs.length; i++) {
		var tabName = tabs[i].getAttribute('name');
		tabs[i].style.display = ( (tabName == targetName) ? 'block' : 'none' );
	}
	return(false);
};

var tabSets = function() {
	var tabs = $('.tabLink');
	if (tabs.length > 0) {
		for (var i=0; i<tabs.length; i++) {
			tabs[i].onclick = tabSetOnClick;
		}
	}
	tabs = null;
};

/* }}} */

$(document).ready(function() {
	error404();
	dropdowns();
	addBackgrounds();
	tooltipMouseover();
	omnitureLoginBounceFilter();
	omnitureChatLinkClick();
	omnitureSupportLinkClick();
	omnitureSupportToolClick();
	omnitureReferralLinkClick();
	omnitureFooterToolbarClick();
	omnitureSignupButtonClick();
	omnitureSidebarVideoClick();
	markupPrep();
	blog_archiveFold();
	animateStats();
	headerImages();
	startCareersImageFade();
	htmlButtons();
	tabSets();
});

Object.extend = function(dest, source) {
	for (var property in source) {
		dest[property] = source[property];
	}
	return dest;
};
