var CFG_SIGNUP_PATH = 'https://signup.apps.rackspace.com/';


/* {{{ error404 */
var error404 = function() {
	$("#error .text").click(function(){
		$(this).css('color', '#000');
		$(this).val("");
	});
};
/* }}} */
	
/* {{{ 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 */
var siteSearch = function() {
    // EE makes my code hurt
    var search = '(Enter Search Term)';
    // 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 == '(Enter Search Term)' || 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);
	});
};
/* }}} */
	
var sendGoogleData = function(obj, e, dataArray) {

	for (key in dataArray) {
		_gaq.push([key, dataArray[key]]);
	}

	// delay next page load to ensure time for tracking pixel on current page
	e.preventDefault(); 
	setTimeout('document.location = "' + obj.href + '"', 100);

}

/* {{{ markupPrep */
var markupPrep = function() {
	var listPrep = function() {
		$('li:last-child').addClass('last');
	};
	
	var tablePrep = function() {
		$('table tr:odd').addClass('alt');
		$('table td:last-child, table th:last-child').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();
	addBackgrounds();
	siteSearch();
	tooltipMouseover();
	markupPrep();
	blog_archiveFold();
	animateStats();
	headerImages();
	startCareersImageFade();
	htmlButtons();
	tabSets();
});

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

