// Fixes the transparent PNGs in IE6
var DD_belatedPNG;
if (DD_belatedPNG) { // Only execute for IE6
	// Selectors need to match what's in the CSS exactly
	DD_belatedPNG.fix('#Content ul.documents li a.pdf, #Content ul.documents li a.video');
	DD_belatedPNG.fix('#Content .productInfographic .largeBox a, #Content .productInfographic .largeBox a span,#Content .productInfographic .smallBox a, #Content .productInfographic .smallBox a span');
	DD_belatedPNG.fix('#Sidebar .faithQuote, #Content ul.academicLogos li img, .solutionsLanding #Sidebar ul.articles li a.html');
	DD_belatedPNG.fix('#Content .tileAndContentBlock .resourceTile p.image img, #Content .threeColFeatureBoxes h3');
	DD_belatedPNG.fix('#Content .devTestingCharacteristics li, img');
}

// Control images that are displayed for a product
var ProductShots = {
	selectedIndex: 0,
	productShots: [],
	init: function() {

		var PS = ProductShots;
		//PS.productShots = $('.productShots');
		PS.productShots = $('div.standardContainer').siblings('div.productShots');
		
		if (PS.productShots.length == 0) return;

		var $lis = PS.productShots.find('ul.thumbnails li');
		if ($lis.length == 0) return;
		
		if ($lis.length == 1) {
			$('ul.thumbnails').attr('style','display: none'); // Hide thumbnail if there's only 1
		} 
		else {
			PS.setupEvents($lis);
			var $selected = $lis.filter('.selected');
			if ($selected.length == 0) $selected = $lis;
			PS.select($selected[0]);
		}
	},
	setupEvents: function($lis) {
		$lis.hover(ProductShots.thumbOver, ProductShots.thumbOut).click(ProductShots.click);
		$('#ProductImage').click(ProductShots.largeClick);
		$("ul.screenshots li a[rel^='prettyPhoto']").click(ProductShots.tabScreenshotClick);
	},
	thumbOver: function(event) {
	},
	thumbOut: function(event) {
	},
	click: function(event) {
		ProductShots.select(this);
	},
	largeClick: function(event) {
		// Convert src from thumb to product image
		var src = $(this).attr('src');
		src = src.replace('-med.png','-large.png');
		src = src.replace('-med.jpg','-large.jpg');
		if ($.prettyPhoto) {
			$.prettyPhoto.open(src, '', $(this).attr('title'));
		}
	},
	tabScreenshotClick: function(event) {
		event.preventDefault();
		var src = $(this).attr("href");
		var caption = $(this).children(':first').attr('title');
		if ($.prettyPhoto) {
			$.prettyPhoto.open(src, '', caption);
		}
	},
	select: function(elm) {
		
		var $selected_lis = $(elm).siblings('.selected') // li.selected
															.removeClass('selected');
		
		$(elm).addClass('selected');

		// Convert src from thumb to product image
		var $img = $(elm).find('> img');
		var src = $img.attr('src');
		src = src.replace('-thumb.png','-med.png');
		src = src.replace('-thumb.jpg','-med.jpg');
		$('#ProductImage').attr( { src: src, title: $img.attr('title') } );
	}
};
$(function() { ProductShots.init(); });

// Convert on-tabbed display into tabbed display and activate tabs
var Tabs = {
	init: function() {
		if (! $.fn.tabs) {
			return;
		}
		var $tabs = $('div.tabs');
		var $tabnav = $tabs.find('ul.tabNav');
		var liClass = "first";
		if ($tabnav.length == 0) {
			$tabnav = $tabs.prepend('<ul class="tabNav selfClear"></li>').find('> ul');
			$tabs	.find('> div')
					.each( function(i) {
						var id = this.id;
						var $h2 = $(this).find('h2');
						var title = '';
						if ($.fn.metadata && $(this).metadata().tabTitle)
							title = $(this).metadata().tabTitle;
						else
						 	title = $h2.html();
						
						$tabnav.append('<li class="'+ liClass +'"><a href="#' + id + '" class="noPopup"><span>' + title + '</span></a></li>');
						$h2.remove();
						liClass = "";
					} );
			$tabnav.find('li:last').addClass('last');
			// Need delay for browsers to get their DOM in order
			setTimeout(function() {
				$tabs.tabs({
					select: function(event, ui) {
						var $nav = $(this).find('ul.tabNav');
						$nav.removeClass('active0 active1 active2 active3 active4').addClass('active' + ui.index);
					}
				});
				$tabs.find('> div').removeClass('hideOnLoad');
				// Scroll back to top if there's a tab to select.
				// Need to do this because we have a delay before tabs are built and browsers will
				// scroll down to where the tab content was before the tab was built.
				if (document.location.hash)
					$.scrollTo(0);
			}, 500);
		}
	}
};
$(document).ready(Tabs.init);

// Convert on-tabbed display into tabbed display and activate event and webcasts tabs on homepage
var EventTabs = {
	init: function() {
		if (! $.fn.tabs) {
			return;
		}
		var $tabs = $('div.eventTabs');
		var $tabnav = $tabs.find('ul.tabNav');
		var liClass = "first";
		if ($tabnav.length == 0) {
			$tabnav = $tabs.prepend('<ul class="tabNav selfClear"></li>').find('> ul');
			$tabs	.find('> div')
					.each( function(i) {
						var id = this.id;
						var $h2 = $(this).find('h2');
						var title = '';
						if ($.fn.metadata && $(this).metadata().tabTitle)
							title = $(this).metadata().tabTitle;
						else
						 	title = $h2.html();
						
						$tabnav.append('<li class="'+ liClass +'"><a href="#' + id + '" class="noPopup"><span>' + title + '</span></a></li>');
						$h2.remove();
						liClass = "";
					} );
			// Need delay for browsers to get their DOM in order
			setTimeout(function() { $tabs.tabs(); }, 500);
		}
	}
};
$(document).ready(EventTabs.init);

// Convert un-tabbed display into tabbed display and activate tabs
var ANTabs = {
	init: function() {
		// Only run if we have tabs
		if (! $.fn.tabs) return;

		var $tabs = $('div.solutionsTabs');
		if ($tabs.length == 0) return;

		var $tabnav = $('<ul class="tabNav selfClear"></ul>');
		$tabs.prepend($tabnav);
		$tabs	.find('> div')
					.each( function(i) {
						var id = this.id;
						// Descending search for header values
						var $header = $(this).find('h2:first');
						if ($header.length == 0)
							$header = $(this).find('h3:first');
						if ($header.length == 0)
							$header = $(this).find('h4:first');
						// Use title value if available
						var title = $header.attr('title') || $header.html();

						$tabnav.append('<li id="' + id + 'Tab"><a href="#' + id + '" class="noPopup"><span>' + title + '</span></a></li>');
						$header.remove();
					});
		// Need delay for browsers to get their DOM in order
		setTimeout(function() {
			$tabs.tabs({
				// Prevent outline on selection
				select: function(event, ui) {
					$(ui.tab).blur();
				},
				show: function(event, ui) {
					$('ul.tabNav').find('.leftOfSelected').removeClass('leftOfSelected');
					$('ul.tabNav').find('li.ui-state-active').prev().addClass('leftOfSelected');
				}
			});
			$tabs.find('.hideOnLoad').removeClass('hideOnLoad');
		}, 500);
		$('#ContentChannel ul.tabNav li:first').addClass('first');
		$('#ContentChannel ul.tabNav li:last').addClass('last');
		$('ul.tabNav').find('li.ui-state-active').addClass('leftOfSelected');
	}
};
$(document).ready(ANTabs.init);


var Todo = {
	init: function() {
		$('a[href*=#todo]').addClass('todo');
	}
};
$(document).ready(Todo.init);

var viewVideoModal = function(e) {
	e.preventDefault();
	// Need to call prettyPhoto to setup the open function if it's not already avail
	// if (! $.fn.prettyPhoto)
	// 	return;
		
	// Reset prettyPhoto to use the standard flash markup code
	var options = {
		theme: 'facebook',
		flash_markup: '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="{width}" height="{height}"><param name="wmode" value="{wmode}" /><param name="allowfullscreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="movie" value="{path}" /><embed src="{path}" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="{width}" height="{height}" wmode="{wmode}"></embed></object>'
	};
	$.prettyPhoto.settings(options);
	$.prettyPhoto.open('/images/homepage/flv_wrapper.swf?width=862&height=485', '', '');
	pageTracker._trackPageview("/homepage/coverity5BugVideo");
};

$(document).ready(function(){
	$('a.bugVideo').click(viewVideoModal);
});

// Benefits Modal window
var $dialog;

$(document).ready(function() {
	$('#Benefits').dialog({
		autoOpen: false,
		draggable: false,
		modal: true,
		bgiframe: false,
		width: 896,
		buttons: {}
	});
	

	$('#Sidebar a.whatWeOffer').click(function(e) {
		e.preventDefault();
		$('#Benefits').dialog('open');
	});
	$('#Benefits a.close').click(function(e) {
		e.preventDefault();
		$('#Benefits').dialog('close');
	});
});

// Customers carousel
$(document).ready(function() {
	$("#Content .moreCustomers .carousel").jCarouselLite({
		btnNext: "#Content .moreCustomers .next a",
		btnPrev: "#Content .moreCustomers .prev a",
		circular: true,
		visible: 1
	});
});

$(document).ready(function() {
	$("#CustomerCarousel").jCarouselLite({
		auto: 5000,
		circular: true,
		speed: 500,
		visible: 1
	});
});

$(document).ready(function() {
	$(".resourcesCarousel").jCarouselLite({
		auto: 0,
		circular: true,
		speed: 500,
		visible: 1,
		btnNext: ".carouselNav .next",
    btnPrev: ".carouselNav .prev",
		btnGo:
    [".carouselNav .1", ".carouselNav .2",
    ".carouselNav .3", ".carouselNav .4"],
		afterEnd: function(a) {
			var index = $(a[0]).index(); 
			if (index > 4) { index = 1;}
			if (index < 1) { index = 4;}
			$('.carouselNav li.active').removeClass('active');
			$('.carouselNav li a.' + index).parent().addClass('active');
    }
	});
});

/*$(document).ready(function() {
	$(".fr #mainPromoContainer, .de #mainPromoContainer").jCarouselLite({
		auto: 10000,
		circular: true,
		visible: 1,
		speed: 0
	});
});*/

/* begin - open new window for external links and pdfs */
$(document).ready(function () {
	if (!$.fn.popupwindow)
		return;
		
	// Open fully qualified links, secure HTTP connection links, PDF links and specific links with class 'popup' in a new browser window
	$('a[href^="http://"],a[href^="https://"],a[href$=".pdf"]')
		.not($('a.noPopup,a.pp_close,a.popup'))
		.popupwindow();
});
/* end - open new window for external links and pdfs */

/* change image in Coverity and HP ingraphic */
$(document).ready(function() {
	$("#Business").hover(
		function() {
			$("#CoverityHPGraphic").attr("src","/images/products/coverity-hp-infographic-business.png");
		},
		function() {
			$("#CoverityHPGraphic").attr("src","/images/products/coverity-hp-infographic-default.png");
		}
	);
	$("#ReleaseManagement").hover(
		function() {
			$("#CoverityHPGraphic").attr("src","/images/products/coverity-hp-infographic-release.png");
		},
		function() {
			$("#CoverityHPGraphic").attr("src","/images/products/coverity-hp-infographic-default.png");
		}
	);
	$("#QualityAssurance").hover(
		function() {
			$("#CoverityHPGraphic").attr("src","/images/products/coverity-hp-infographic-qa.png");
		},
		function() {
			$("#CoverityHPGraphic").attr("src","/images/products/coverity-hp-infographic-default.png");
		}
	);
	$("#Development").hover(
		function() {
			$("#CoverityHPGraphic").attr("src","/images/products/coverity-hp-infographic-dev.png");
		},
		function() {
			$("#CoverityHPGraphic").attr("src","/images/products/coverity-hp-infographic-default.png");
		}
	);
	$("#Requirements").hover(
		function() {
			$("#CoverityHPGraphic").attr("src","/images/products/coverity-hp-infographic-req.png");
		},
		function() {
			$("#CoverityHPGraphic").attr("src","/images/products/coverity-hp-infographic-default.png");
		}
	);
});

var DevTestingWidget = {
	widget: [],
	graphics: {
		management: '/images/development-testing/diagram-management.png',
		development: '/images/development-testing/diagram-development.png',
		qa: '/images/development-testing/diagram-qa.png',
		security: '/images/development-testing/diagram-security.png'
	},
	init: function() {
		var $$ = DevTestingWidget.widget = $('.devTestingWidget');
		if ($$ == 0) return;

		$$.find('dt em').bind('mouseover', DevTestingWidget.mouseoverTrigger);
		$$.find('#Management').bind('mouseover', function() { DevTestingWidget.mouseoverImage('management'); });
		$$.find('#Development').bind('mouseover', function() { DevTestingWidget.mouseoverImage('development'); });
		$$.find('#Security').bind('mouseover', function() { DevTestingWidget.mouseoverImage('security'); });
		$$.find('#QualityAssurance').bind('mouseover', function() { DevTestingWidget.mouseoverImage('qa'); });

		// Preload graphics
		var img = new Image();
		jQuery.each(DevTestingWidget.graphics, function(key, value) {
			img.src = value;
		});
	},
	mouseoverTrigger: function(event) {
		DevTestingWidget.activate($(this).parent());
	},
	mouseoverImage: function(klass) {
		DevTestingWidget.activate(DevTestingWidget.widget.find('dt.' + klass));
	},
	activate: function($$) {
		if ($$.hasClass('active')) return;

		$$.addClass('active').siblings().removeClass('active');
		$$.siblings('dd').hide().end().next().show();

		var $graphic = $('#InfographicHolder');
		if ($$.hasClass('management')) {
			$graphic.css({backgroundImage: 'url(' + DevTestingWidget.graphics['management'] + ')'});
		}
		else if ($$.hasClass('development')) {
			$graphic.css({backgroundImage: 'url(' + DevTestingWidget.graphics['development'] + ')'});
		}
		else if ($$.hasClass('qa')) {
			$graphic.css({backgroundImage: 'url(' + DevTestingWidget.graphics['qa'] + ')'});
		}
		else if ($$.hasClass('security')) {
			$graphic.css({backgroundImage: 'url(' + DevTestingWidget.graphics['security'] + ')'});
		}		
	}
};
$(document).ready(DevTestingWidget.init);

(function($) {
    var FMACarousel = {
        init: function() {
            if (!$.fn.carouFredSel) return;

            $('.home #mainPromoContainer').each(function() {
                $(this).append('<ul class="carouselNav"/>');
                $(this).find('li.hideOnLoad').removeClass('hideOnLoad');
                $(this).find('ul.carousel').carouFredSel({
                    items: 1,
                    scroll: {
                        pauseOnHover: true
                    },
                    auto: 7000,
                    pagination: {
                        container: "ul.carouselNav",
                        anchorBuilder: function( nr ) {
                            return '<li class="nav"><a href="#">'+nr+'</a></li>';
                        }
                    }
                });
                $(this).find('li.nav').bind('click', function(event) {
                    event.preventDefault();
                });
            });
        }
    };
    $(FMACarousel.init);
})(jQuery);

(function($) {
    var HomeCustomerCarousel = {
        init: function() {
            if (!$.fn.carouFredSel) return;
           
            $('.home #FeaturedCustomers').each(function() {
                $(this).find('.carouselWrapper').append('<div class="prev"/><div class="next"/>');
                $(this).find('li.hideOnLoad').removeClass('hideOnLoad');
                $(this).find('ul.carousel').carouFredSel({
                    items: 1,
                    scroll: {
                        pauseOnHover: true,
                        fx: "fade"
                    },
                    auto: {
                        pauseDuration: 7000,
                        delay: 2000
                    },
                    prev: "#FeaturedCustomers div.prev",
                    next: "#FeaturedCustomers div.next"
                });
            });
        }
    };
    $(HomeCustomerCarousel.init);
})(jQuery);

(function($) {
    $(function() {
        $('#Spotlight a.video').prettyPhoto();
    });
})(jQuery);
