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

/* Special search behavior */
var defaultSearchVal = '';
var Search = {
	prompt: "Search", // default value - should get real value from markup
	init: function() {
		defaultSearchVal = jQuery('#SearchForm input.searchField').attr("rel");
		jQuery('#SearchForm input.searchField').val(defaultSearchVal);
		Search.prompt = jQuery('#SearchForm input.searchField').focus(Search.focus).blur(Search.blur).val();
	},
	focus: function() { if (this.value == defaultSearchVal) { this.value = ''; } },
	blur: function() { if (this.value.length == 0) { this.value = defaultSearchVal; } }
};
$(document).ready( Search.init );



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('a.sampleButton, a.sampleButton span');
	DD_belatedPNG.fix('#HomeMastPromos .info a.promoButton, #HomeMastPromos .info a.promoButtonTall, #HomeMastPromos .info a.promoButton span');
}

/* begin - Navigation Primary */
var NavigationPrimary = {
  init: function() {    
		var c = this;
		var n = $('#NavigationPrimary ul');
		
		// 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); });

		$('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 */

// 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.tabs');
		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');
						if (title) {
							$header.attr('title', '');
						} else {
							title = $header.html();
							$header.remove();
						}

						$tabnav.append('<li id="' + id + 'Tab"><a href="#' + id + '" class="noPopup"><span>' + title + '</span></a></li>');
					});
		// Need delay for browsers to get their DOM in order
		setTimeout(function() {
			$tabs.tabs({
				// Prevent outline on selection
				select: function(event, ui) {
					var $$ = $(ui.tab);
					$$.blur();
					if ($$.parent().hasClass('last')) {
						$$.parents('ul:first').addClass('lastTabActive');
					} else {
						$$.parents('ul:first').removeClass('lastTabActive');
					}
				}
			});
			$tabnav.find('li:first').addClass('first');
			$tabnav.find('li:last').addClass('last');
			$tabs.find('.hideOnLoad').removeClass('hideOnLoad');
			// Only move to the top of the page when the tabs are present so not to affect real anchor links.
			var tabsPresent = $('div.tabs').size(this);
			if (tabsPresent > 0)
			{
				// Move to the top of the page
				window.scrollTo(0,0);
			}
		}, 500);
	
		$('a.tabLink').live('click', function(e) {
			e.preventDefault;
			var hash = this.hash;
			if (hash.substr(0, 1) != '#')
				hash = '#' + hash;
			$tabs.tabs('select', hash);
		});
	}
};
$(document).ready(ANTabs.init);

// Convert un-tabbed display into tabbed display and activate tabs
var SecondaryNav = {
	init: function() {
		$('#NavigationSecondary h3 a').click(function(e) {
			if ($('#NavigationSecondary h3 a').hasClass('collapsed')) {
				$('#NavigationSecondary ul').slideDown();
				$('#NavigationSecondary h3 a').removeClass('collapsed');

			} else  {
				$('#NavigationSecondary ul').slideUp();
				$('#NavigationSecondary h3 a').addClass('collapsed');
			}
			return false;
		}).each(function() {
			if ($('#NavigationSecondary h3 a').hasClass('collapsed')) {
				$('#NavigationSecondary ul').show();
				$('#NavigationSecondary h3 a').removeClass('collapsed');
			} else  {
				$('#NavigationSecondary ul').hide();
				$('#NavigationSecondary h3 a').addClass('collapsed');
			}
			return false;
		});
		$('#NavigationSecondary h3 a').removeClass('collapsed');
		$('#NavigationSecondary ul').show();
	}
};
$(document).ready(SecondaryNav.init);

/* begin - Global Navigation */
var GlobalNav = {
  init: function() {    
		var c = this;
		var n = $("#Global ul");
		
		// 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'); }
};
/* end - Global Navigation */
$(document).ready(function () {
    GlobalNav.init();
});

var HomeMastCarousel = {
    carousel: null,
    paused: false,
    clicked: 0,
	init: function() {
		if ($('#HomeMast').length > 0)
			HomeMastCarousel.setup();
	},
	setup: function() {
		$('#HomeMast ul.carousel').each(function(i) {
			$(this).find('li.hideOnLoad').removeClass('hideOnLoad').css({opacity: .001});
			$(this).jcarousel({
				wrap: 'last',
				visible: 1,
				scroll: 1,
				itemVisibleInCallback: HomeMastCarousel.itemVisibleInCallback,
                initCallback: HomeMastCarousel.initCallback,
                animation: 0
            }).after('<ul class="carouselNav"><li class="one active">1</li><li class="two">2</li><li class="three">3</li></ul>');
            $('ul.carouselNav li')    .live('click', HomeMastCarousel.navClick)
                                    .live('mouseover', HomeMastCarousel.navMouseover)
                                    .live('mouseout', HomeMastCarousel.navMouseout);
        });
        $('#HomeMast').live('mouseover', HomeMastCarousel.mastMouseover)
                      .live('mouseout', HomeMastCarousel.mastMouseout);
    },

    /* Called when the image/slide loads. First it fades in the new image, then
        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 and the process starts over again.
    */
    itemVisibleInCallback: function(c, el, i, state) {
        $('ul.carouselNav').find('li.active').removeClass('active').end().find('li:eq(' + (i - 1) + ')').addClass('active');
        $(el).fadeTo('slow', 1.0, function() { HomeMastCarousel.fadeInCallback(c, el, i, state); });
    },
    fadeInCallback: function(c, el, i, state) {
        if (HomeMastCarousel.paused) {
            setTimeout(function() { HomeMastCarousel.fadeInCallback(c, el, i, state); }, 500);
            return;
        }
        setTimeout(function() {
            if (HomeMastCarousel.paused) {
                setTimeout(function() { HomeMastCarousel.fadeInCallback(c, el, i, state); }, 500);
                return;
            }
            $(el)
                     // Must animate almost to 0, cause if we go to 0, then the element
                    // gets display="none" and it auto switches to the next slide
                    .fadeTo('slow', 0.001, function() {
                        if (HomeMastCarousel.clicked == 0)
                            c.next();
                        else
                            HomeMastCarousel.clicked--;
                    } );
        }, 5000);
    },
    mastMouseover: function(e) { HomeMastCarousel.paused = true; },
    mastMouseout: function(e) { HomeMastCarousel.paused = false; },
    initCallback: function(carousel) { HomeMastCarousel.carousel = carousel; },
    navClick: function(e) {
        HomeMastCarousel.clicked++;
        HomeMastCarousel.carousel.scroll($.jcarousel.intval($(this).text()));
    },
    navMouseover: function(e) { $(this).addClass('hover'); },
    navMouseout: function(e) { $(this).removeClass('hover'); }
};
$(document).ready(HomeMastCarousel.init);

var HomeMastButtons = {
	init: function() {
		if ($('#HomeMastButtons').length > 0)
			HomeMastButtons.setup();
	},
	setup: function() {
		$('#HomeMastButtons > ul > li')
			.hover(HomeMastButtons.mouseover, HomeMastButtons.mouseout)
			.find('.hideOnLoad')
				.hide()
				.removeClass('hideOnLoad');
	},
	mouseover: function(event) {
		$(this).addClass('hover').find('.buttonBanner').show();
	},
	mouseout: function(event) {
		$(this).removeClass('hover').find('.buttonBanner').hide();
	}
};
$(document).ready(HomeMastButtons.init);

/* begin - open new window for external links and pdfs */
$(document).ready(function () {
        // 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],a.popup')
			.not($('a.noPopup,a[href^=http://www2.serena.com],#NavigationPrimaryBlog a,a[href^=http://support.serena.com]'))
			.popupwindow(); 
	});
/* end - open new window for external links and pdfs */

$(document).ready(function() {
	$('.latestNewsEvents').accordion({
		change: function(event, ui) {
			ui.newHeader.blur();
		}
	});
});

var LogosAndQuotes = {
	init: function() {
		if ($('#LogosAndQuotes').length > 0)
			LogosAndQuotes.setup();
	},
	setup: function() {
		$('#LogosAndQuotes a').live('mouseover mouseout', LogosAndQuotes.hover);
		$('#LogosAndQuotes .hideOnLoad').hide().removeClass('hideOnLoad');
	},
	hover: function(event) {
		if (event.type == 'mouseover')
			$(this).next().show();
		else
			$(this).next().hide();
	}
};
$(document).ready(LogosAndQuotes.init);

var ProfileLogIn = {
	init: function() {
		$('#Toolbar a.profile').bind('click', ProfileLogIn.click);
	},
	click: function(e) {
		e.preventDefault();
		var $$ = $(this).blur().parent().find('div.content');
		if ($$.is(':visible')) {
			$('#Toolbar').removeClass('profileLoginOpen');
			$$.hide();
		} else {
			$('#Toolbar').addClass('profileLoginOpen');
			$$.show();
		}
	}
};
$(document).ready(ProfileLogIn.init);

$(document).ready(function() {
	$('.imageBlock a, p.center a').not('.nofancybox').fancybox();
});
