// Fix background image flickering in IE
try {
  document.execCommand('BackgroundImageCache', false, true);
} catch(e) { }

/* begin - Navigation Primary */
var NavigationPrimary = {
  init: function() {    
		var c = this;
		var n = $('#NavigationPrimary');
		
		// Use bgiframe to fix dropdowns over selects if it's available.
		$.fn.bgiframe && $('li', n).bgiframe();

		// Mark parent elements so that we can style them with CSS
		$('> li', n).each(function() { c.markParents(this); });
  	
  	// Use the hoverintent plugin if it's available
  	if ($.fn.hoverIntent)
    {
  	  $('li', n).hoverIntent( {
  	    sensitivity: 1,
  	    over: this.mouseenter,
  	    out: this.mouseleave,
  	    timeout: 100
  	  });
    }
  	else
  	  $('li', n).hover(this.mouseenter, this.mouseleave);
  },
  markParents: function(li) {
    var c = this;
    if ($('> ul', li).size() > 0)
	    $(li).addClass('parent').find('> a').addClass('parent').end().find('> ul li').each( function() { c.markParents(this); });
	},
	mouseenter: function() { $(this).addClass('over').children('a').addClass('over'); },
	mouseleave: function() { $(this).removeClass('over').children('a').removeClass('over'); }
	
};
$(function() { NavigationPrimary.init(); });
/* end - Primary Navigation */

// Prevent flash of content on page load
document.writeln('<style type="text/css">div.additionalContent { display: none; }</style>');
var ExpandableContent = {
	expand: function(event) {
		event.preventDefault();
		var $elm = $(this).parent();
		ExpandableContent.expandBlock($elm);
	},
	expandBlock: function(elm) {
		$(elm).addClass('expanded')
			.find('a.collapse').show().end()
			.find('a.expand').hide().end()
			.find('div.additionalContent').show();		
	},
	collapse: function (event) {
		event.preventDefault();
		var $elm = $(this).parent();
		ExpandableContent.collapseBlock($elm);
	},
	collapseBlock: function(elm) {
		$(elm).removeClass('expanded')
			.find('a.expand').show().end()
			.find('a.collapse').hide().end()
			.find('div.additionalContent').hide();		
	},
	toggle: function(id) {
		var $elm = $('#' + id);
		if ($elm.length == 0) return;
		if ($elm.hasClass('expanded')) {
			this.collapseBlock($elm);
		} else {
			this.expandBlock($elm);
		}
	},
	init: function(scope) {
		var c = new Array();
		if (scope != null)
			c = $('ul.expandableContent', $(scope));
		else
			c = $('ul.expandableContent');			

		if (c.length == 0 || c.is('.inited'))
			return;
		c.addClass('inited');

		var lis = $('> li', c)
			.prepend('<a href="#expand" class="expand">+</a><a href="#collapse" class="collapse" style="display: none;">-</a>')
			.find('div.additionalContent').hide().end();
		lis.find('a.expand').bind('click', this.expand);
		lis.find('a.collapse').bind('click', this.collapse);
	}
};
$(function() { ExpandableContent.init(); });

// From: http://www.webdeveloper.com/forum/showthread.php?t=148581
function absPath(url){
	// Only convert relative paths
	if (url.substr(0, 1) != '.')
		return url;
	var Loc = location.pathname;
	Loc = Loc.substring(0, Loc.lastIndexOf('/'));
	while (/^\.\./.test(url)){		 
		Loc = Loc.substring(0, Loc.lastIndexOf('/'));
		url= url.substring(3);
	}
	return Loc + '/' + url;
}

$tabs = null;
in_select = false;
start_tab = null;
in_pageload = false;
//document.write('<script type="text/javascript" src="/javascript/jquery.history.js"></script>');
// PageLoad function
// This function is called when:
// 1. after calling $.historyInit();
// 2. after calling $.historyLoad();
// 3. after pushing "Go Back" button of a browser
function pageload(hash) {
	in_page_load = true;
	// hash doesn't contain the first # character.
	if(hash) {
		// restore ajax loaded state
		if ($tabs)
			$tabs.tabs('select', hash);
	} else {
		// start page
		if ($tabs && start_tab != null) {
			$tabs.tabs('select', start_tab);
		}
	}
	in_page_load = false;
}

$(document).ready(function(){
	// Initialize history plugin.
	// The callback is called at once by present location.hash. 
	$.historyInit(pageload);
	
	$("ul.tabNav li").each(function(i, li) {
		if ($(li).hasClass('ui-tabs-selected'))
			start_tab = i;
	});
	if (start_tab == null)
		start_tab = 0;

	$tabs = $("ul.tabNav").tabs({
		cache: true,
		cleanResponse: function(event, ui) {
			// Strip scripts to prevent problems
			ui.response = ui.response.replace(/<script(.|\s)*?\/script>/g, "");

			var contentId = $(ui.tab).attr('contentId');
			if (contentId)
				ui.response = jQuery("<div/>").append(ui.response).find('#' + contentId);
		},
		load: function(event, ui) {
			ExpandableContent.init($(ui.panel));
		},
		select: function(event, ui) {
			if (in_select) return false;
			in_select = true;
			// Track remote tab loads
			var url = $.data(ui.tab, 'load.tabs');
			if (url != null) {
				url = absPath(url);
				var protocol = $(ui.tab).attr('urlProtocol') || 'http:';
				// Can't do a cross-protocol load via AJAX so need to 
				// actually reload the page.
				if (protocol != location.protocol) {
					location.href = protocol + '//' + location.hostname + url;
					return false;
				}
				try {
					var pageTracker = _gat._getTracker("UA-4413916-2");
					pageTracker._trackPageview(url);
				} catch(err) {}
			}
			if (! in_page_load) {
				var hash = ui.tab.hash;
				hash = hash.replace(/^.*#/, '');
				// pageload is called at once.
				$.historyLoad(hash);
			}
			in_select = false;
		}
	});
});

function highlightDiagram(thediagram,backgroundpos) {
	$(document).ready(function(){
		$("#ProductsInfographicDefaultText").css("display","none");
		$("#ProductsInfographicAdvancedServerText").css("display","none");
		$("#ProductsInfographicStandardServerText").css("display","none");
		$("#ProductsInfographicSQLText").css("display","none");
		$("#ProductsInfographic" + thediagram + "Text").css("display","block");
		$("#MainImgRollOver").css("background-position",backgroundpos);
	});
}

function servicesDiagram(thediagram) {
	$(document).ready(function(){
		$("#ServicesIntroText").css("display","none");
		$("#TrainingText").css("display","none");
		$("#CertificationText").css("display","none");
		$("#PartnersText").css("display","none");
		$("#ConsultingText").css("display","none");
		$("#SupportText").css("display","none");
		$("li#TrainingImage").css("background-position","0 0");
		$("li#CertificationImage").css("background-position","0 0");
		$("li#PartnersImage").css("background-position","0 0");
		$("li#ConsultingImage").css("background-position","0 0");
		$("li#SupportImage").css("background-position","0 0");

		$("#" + thediagram + "Text").css("display","block");
		$("li#" + thediagram + "Image").css("background-position","-125px 0");
	});
}

// Fixes for how IE7 deals with opacity on text.
// More info:
//   * http://www.nabble.com/strange-ie7-related-font-behaviour---jQ-ie7-bug--td20825761s27240.html
//   * http://jquery.malsup.com/fadetest.html
// Solution adapted to work with jQuery 1.3 which no longer has jQuery.browser
jQuery.fn.fadeIn = function(speed, callback) { 
    return this.animate({opacity: 'show'}, speed, function() { 
        if (! jQuery.support.opacity)  
            this.style.removeAttribute('filter');  
        if (jQuery.isFunction(callback)) 
            callback();  
    }); 
}; 
 
jQuery.fn.fadeOut = function(speed, callback) { 
    return this.animate({opacity: 'hide'}, speed, function() { 
        if (! jQuery.support.opacity)  
            this.style.removeAttribute('filter');  
        if (jQuery.isFunction(callback)) 
            callback();  
    }); 
}; 
 
jQuery.fn.fadeTo = function(speed,to,callback) { 
    return this.animate({opacity: to}, speed, function() { 
        if (to == 1 && ! jQuery.support.opacity)  
            this.style.removeAttribute('filter');  
        if (jQuery.isFunction(callback)) 
            callback();  
    }); 
}; 

$(function() {
  /*
	A bit of a complicated scenario: 
	 - an_fadeOut is called when the image/slide loads. It uses jQuery's 
	  animate function to delay before fading out the image. Once the
	  image has faded out there is a callback to tell the carousel to
	  transition to the next slide/image.
	 - an_restore is called after the image/slide is no longer visible.
	  Since the image/slide was faded to almost nothing, we need to
	  restore it so that it will be visible next time it is displayed.
  */
  var an_fadeOut = function(c, el, i, state) {
	$(el).animate({width: '210px'}, 10000) // milliseconds before we fade
		  .fadeTo('slow', 0, function() { c.next(); });
  };
  var an_restore = function(c, el, i, state) { 
		$(el).css('opacity', 1.0);
    if (! jQuery.support.opacity)  
        el.style.removeAttribute('filter');  
  };

  // Find the number of quotes in the right channel quote box
  var quoteCount = $('#Quotes > .content > ul > li').size();
  // Get a random number for the start point of the rotating quote box in the right channel quote box
  var startingQuote = Math.floor(Math.random() * quoteCount);
  // Need to call jcarousel on the parent element to the UL
	if ($.fn.jcarousel) {
	  $('#Quotes > div').jcarousel({
	  		scroll: 1,
	  		animation: 0,
	  		buttonNextHTML: null,
	  		buttonPrevHTML: null,
	  		itemVisibleInCallback: an_fadeOut,
	  		itemVisibleOutCallback: an_restore,
	  		visible: 1,
	  		start: startingQuote,
	  		wrap: 'both',
	  		// Don't auto scroll because the transition is handled by visible in callback
	  		auto: 0
	  });
	}
});

jQuery.extend(jQuery.expr[':'], {
		Contains: function(elem, i, match, array) {
			return (elem.textContent || elem.innerText || "").toLowerCase()
				.indexOf((match[3]||"").toLowerCase()) >= 0;
		}
});

// JS includes to support showing search terms
//document.write('<script src="/javascript/jquery.scrollTo-min.js" type="text/javascript"></script>');
//document.write('<script src="/javascript/jquery.url.packed.js" type="text/javascript"></script>');
var ShowSearchTerm = {
	init: function(test_term) {
		if (! $.url) return;
		
		if (document.referrer)
			$.url.setUrl(document.referrer);
		var term = test_term 
								|| this.unescape($.url.param('q')
									|| $.url.param('p'));
		if (! term) return;
		var $elm = $(':Contains(' + term + ')');
		if ($elm.length > 0) {
			var elm = $elm.get(0);
			var $exp_element = $elm.parents('div.additionalContent').parents('.content:first').parent();
			if ($exp_element.length == 1) {
				elm = $exp_element.get(0);
				ExpandableContent.expandBlock($exp_element);
			}
			if ($.fn.scrollTo) {
				$.scrollTo(elm, 800);
			}
		}
	},
	unescape: function(str) {
		if (str == null) return str;
		str = str.replace(/\+/, ' ');
		return unescape(str);
	}
};
$(document).ready( function() { ShowSearchTerm.init(); } );
