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

/* Special search behavior */
var Search = {
	prompt: "Search", // default value - should get real value from markup
	init: function() {
		Search.prompt = jQuery('#q').focus(Search.focus).blur(Search.blur).val();
	},
	focus: function() { if (this.value == Search.prompt) { this.value = ''; } },
	blur: function() { if (this.value.length == 0) { this.value = Search.prompt; } }
};
$(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('#NavigationPrimary li li.first a, #NavigationPrimary li li.last a, li#PrimaryNavigationRequest-trial a');
	DD_belatedPNG.fix('#Mast .button, #Mast .button a, #NextSteps ul li a, #ContentFooter, #WrapperContentContainer');
	DD_belatedPNG.fix('body.home #Content .quote, body.home #Content .quote q, cite#GartnerLogo, .popupNavigation li a');
	DD_belatedPNG.fix('#Content table.comparison span.checkmark, #Content table.comparison span.xmark');
	DD_belatedPNG.fix('#Content .resourceItem p.image a img');
}

/* 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); });
  	
  	// 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 */

/* Carousel for mast on homepage  */
var HomeCarousel = {
	init: function() {
		$("body.home #Carousel ul").each(function(i) {
			var $$ = $(this);
			$$.find('li.hideOnLoad').removeClass('hideOnLoad');
			$$.jcarousel({								   
				scroll: 1,
				auto: 12,
				// visible: 1,
				buttonNextHTML: null,
				buttonPrevHTML: null,
				wrap: 'both',
				initCallback: HomeCarousel.initCallback,
				itemVisibleInCallback: {onBeforeAnimation: HomeCarousel.itemVisibleInCallback}
			});
			var item_count = $$.children().length;
		});
	},
	initCallback: function(carousel) {
		$('body.home #Mast #Carousel ul li img').css('display','block');
		$('.mastNav a.control').bind('click', function() {
			carousel.scroll(jQuery.jcarousel.intval($(this).text()));
			$(this).addClass("active").siblings().removeClass('active');
			// Stop the auto play if the user uses the navigation
			carousel.startAuto(0);
			return false;
		});
	
		$('.mastNav a.next').bind('click', function() {
			carousel.next();
			// Stop the auto play if the user uses the navigation
			carousel.startAuto(0);
			return false;
		});

		$('.mastNav a.previous').bind('click', function() {
			carousel.prev();
			// Stop the auto play if the user uses the navigation
			carousel.startAuto(0);
			return false;
		});		
	},
	itemVisibleInCallback: function(carousel, item, i, state, evt) {
		$('.mastNav a.control').removeClass("active").filter(':contains(' + i + ')').addClass('active');
	}
};
$(document).ready(HomeCarousel.init);

var PopupNavigation = {
	init: function() {
		$('div.popupNavigation .navBlock').hover(
			function() {
				$(this).addClass('hover');
			},
			function() {
				$(this).removeClass('hover');
			}
		).find('a').click(function() {
			$(this).parents('.navBlock').removeClass('hover');
		});
	}
};
$(document).ready(PopupNavigation.init);

var swfobject;
$(document).ready(function() {
	var $$ = $('#YouTubePlayer20090504');
	var params = {};
	var atts = {};
	if ($$.length > 0 && swfobject) {
		params = { 
			allowScriptAccess: "always",
			wmode: "transparent"
		};
		atts = { id: "YouTubePlayer20090504" };
		swfobject.embedSWF("http://www.youtube.com/v/6ZksIVW7kUI&amp;hl=en&amp;fs=1", "YouTubePlayer20090504", "425", "344", "8", null, null, params, atts);
	}

	$$ = $('#YouTubePlayer20100309');
	if ($$.length > 0 && swfobject) {
		params = { 
			allowScriptAccess: "always",
			wmode: "transparent"
		};
		atts = { id: "YouTubePlayer20100309" };
		swfobject.embedSWF("http://www.youtube.com/v/2ggzt7Rvyek&amp;hl=en_US&amp;fs=1&amp;", "YouTubePlayer20100309", "640", "385", "8", null, null, params, atts);
	}
});

// Convert on-tabbed display into tabbed display and activate tabs
$(document).ready(function() {
	var $tabs = $('div.tabs');
	if ($tabs.length == 0)
		return;

	var $tabnav = $tabs.find('ul.tabNav');
	if ($tabnav.length == 0) {
		$tabnav = $tabs.prepend('<ul class="tabNav selfClear"></ul>').find('> ul');
		$tabs	.find('> div')
			.each( function(i) {
				var id = this.id;
				var title = $(this).metadata().tabTitle;
				$tabnav.append('<li><a href="#' + id + '" class="noPopup"><span>' + title + '</span></a></li>');
			});
			// Need delay for browsers to get their DOM in order
			setTimeout(
				function() {
					$tabs.tabs();

					// Enable links to tabs to activate tab
					$('a.tabLink').click(function() { // bind click event to link
						$tabs.tabs('select', this.hash);
						return false;
					});

					// 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
			);
	}
});

var HideDefaultText = {
	init: function() {
		$('input.hasDefault').each(function() {
			// Save default text in data for element
			$(this).data('default_value', this.value);
		}).focus(HideDefaultText.focus).blur(HideDefaultText.blur);
		$('textarea.hasDefault').each(function() {
			// Save default text in data for element
			$(this).data('default_value', this.value);
		}).focus(HideDefaultText.focus);
	},
	focus: function() {
		// Get default text from data
		var default_text = $(this).data('default_value');
		if (this.value == default_text) { this.value = ''; }
	},
	blur: function() {
		// Get default text from data
		var default_text = $(this).data('default_value');
		if (this.value.length == 0) {
			this.value = default_text;
		}
	}
};
$(document).ready(HideDefaultText.init);

var setupMultiTaskingInCloudWebinar = function() {
	var options = {
		theme: 'facebook',
		flash_markup: '<object id="webinarplayer" width="1024" height="768" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" ><param name="type" value="application/x-shockwave-flash"/><param name="allowfullscreen" value="true"/><param name="allowscriptaccess" value="always"/><param name="quality" value="best"/><param name="scale" value="noscale" /><param name="wmode" value="transparent"/><param name="bgcolor" value="#000000"/><param name="salign" value="lt"/><param name="movie" value="http://resources.skytap.com/webinars/development-webinar.swf"/><embed name="webinarplayer" PLUGINSPAGE="http://www.macromedia.com/go/getflashplayer" allowfullscreen="true" allowscriptaccess="always" bgcolor="#000000" width="1024" height="768" quality="best" wmode="transparent" scale="noscale" salign="lt" src="http://resources.skytap.com/webinars/development-webinar.swf" type="application/x-shockwave-flash" /></object>'
	};
	if ($.fn.prettyPhoto) {
		$("a[rel^='MultiTaskingInCloudWebinar']").prettyPhoto(options);
	}
};
jQuery(document).ready(setupMultiTaskingInCloudWebinar);


/* begin - open new window for external links and pdfs */
	$(function() {
		$('#Wrapper a[href^=http://]').not($('a.noPopup')).popupwindow(); // Fully qualified links
		$('#Wrapper a[href^=https://]').not($('a.noPopup')).popupwindow(); // Secure HTTP connection links
		$('#Wrapper a[href$=.pdf]:not([href^=http://])').popupwindow(); // PDFs by URL
		$('#Wrapper a.popup').popupwindow(); // specific links
	});
/* end - open new window for external links and pdfs */

/* Open pictures and screenshots in a modal window */
$(document).ready(function(){
	$("a[rel^='prettyPhoto']").prettyPhoto({theme: 'facebook', allowresize: false});
});




/* Produt Tour Carousel */
function mycarousel_initCallback(carousel) {
	var min_visible = 1;
	var max_visible = 4;
	jQuery('#ProductTour .previous').bind('click', function() {
		if ($('#ProductTourCarousel').find('li.selected').hasClass('first') != true) {
			var current_item = $('#ProductTourCarousel').find('li.selected').attr('jcarouselindex');
			if (current_item == min_visible) {
				carousel.prev();
				max_visible--; 
				min_visible--;
			}
			$('#ProductTourCarousel').find('li.selected').removeClass('selected').addClass('shadowed').prev().removeClass('shadowed').addClass('selected');
			display_product_image();
		}
	});
	jQuery('#ProductTour .next').bind('click', function() {
		if ($('#ProductTourCarousel').find('li.selected').hasClass('last') != true) {
			var current_item = $('#ProductTourCarousel').find('li.selected').attr('jcarouselindex');
			if (current_item == max_visible) {
				carousel.next();
				max_visible++; 
				min_visible++;
			}
			$('#ProductTourCarousel').find('li.selected').removeClass('selected').addClass('shadowed').next().removeClass('shadowed').addClass('selected');
			display_product_image();
		}
	});
	jQuery('#ProductTourCarousel li').bind('click', function() {
		$('#ProductTourCarousel').find('li').removeClass('selected').addClass('shadowed');
		$(this).removeClass('shadowed').addClass('selected');
		display_product_image();
	});
};

function display_product_image() {
	var src = $('#ProductTourCarousel').find('li.selected > img').attr('src');
	src = src.replace('_thumb.jpg','.jpg');
	$('#ProductScreenshot img').attr('src',src);
	var href = src;
	href = href.replace('.jpg','_lg.jpg');
	$('#ProductScreenshot a').attr('href',href);
}

var ProductTourCarousel = {
	init: function() {
		$('#ProductTourCarousel li').addClass('shadowed');
		$('#ProductTourCarousel li:first').removeClass('shadowed').addClass('selected');
		jQuery('#ProductTourCarousel').jcarousel({
			scroll: 1,
			initCallback: mycarousel_initCallback
		});
	}
};

$(document).ready(ProductTourCarousel.init);
/* end - Produt Tour Carousel */

jQuery.validator.addMethod(
	"requiredForUS",
	function(value, element) {
		if ($(element).parents('form:first').find('select[name=country]').val() == 'United States') {
			return value != '';
		}
		return true;
	},
	"Please select a state"
);

jQuery.validator.addMethod("phoneIntl", function(phone_number, element) {
    phone_number = phone_number.replace(/\s+/g, ""); 
	return this.optional(element) || phone_number.length > 9 &&
		phone_number.match(/^[-+\d()]+$/);
}, "Please specify a valid phone number");

$(document).ready(function() {
	// HowToBuyForm validation
	$('#HowToBuyForm').find('#country').change(function() {
		// alert("changed");
		if ($(this).val() == 'United States') {
			$('#HowToBuyForm').find('#state').parents('div:first').show();
		} else {
			$('#HowToBuyForm').find('#state').parents('div:first').hide();		
		}
	}).each(function() {
		if ($(this).val() == 'United States') {
			$('#HowToBuyForm').find('#state').parents('div:first').show();
		} else {
			$('#HowToBuyForm').find('#state').parents('div:first').hide();
		}
	});
	$('#HowToBuyForm').validate( { errorElement: 'span' } );
	
	// Contact Us Form validation
	$('#ContactUsForm').find('#country').change(function() {
		// alert("changed");
		if ($(this).val() == 'United States') {
			$('#ContactUsForm').find('#state').parents('div:first').show();
		} else {
			$('#ContactUsForm').find('#state').parents('div:first').hide();		
		}
	}).each(function() {
		if ($(this).val() == 'United States') {
			$('#ContactUsForm').find('#state').parents('div:first').show();
		} else {
			$('#ContactUsForm').find('#state').parents('div:first').hide();
		}
	});
	$('#ContactUsForm').validate( { errorElement: 'span' } );
	
	// TCO Calculator Form validation
	$('#TCOCalculatorForm').find('#country').change(function() {
		// alert("changed");
		if ($(this).val() == 'United States') {
			$('#TCOCalculatorForm').find('#state').parents('div:first').show();
		} else {
			$('#TCOCalculatorForm').find('#state').parents('div:first').hide();		
		}
	}).each(function() {
		if ($(this).val() == 'United States') {
			$('#TCOCalculatorForm').find('#state').parents('div:first').show();
		} else {
			$('#TCOCalculatorForm').find('#state').parents('div:first').hide();
		}
	});
	$('#TCOCalculatorForm').validate( { errorElement: 'span' } );
	
	// Resource Kit Form validation
	$('#ResourceKitForm').find('#country').change(function() {
		// alert("changed");
		if ($(this).val() == 'United States') {
			$('#ResourceKitForm').find('#state').parents('div:first').show();
		} else {
			$('#ResourceKitForm').find('#state').parents('div:first').hide();		
		}
	}).each(function() {
		if ($(this).val() == 'United States') {
			$('#ResourceKitForm').find('#state').parents('div:first').show();
		} else {
			$('#ResourceKitForm').find('#state').parents('div:first').hide();
		}
	});
	$('#ResourceKitForm').validate( { errorElement: 'span' } );
	
	// Support Form validation
	$('#SupportForm').find('#country').change(function() {
		// alert("changed");
		if ($(this).val() == 'United States') {
			$('#SupportForm').find('#state').parents('div:first').show();
		} else {
			$('#SupportForm').find('#state').parents('div:first').hide();		
		}
	}).each(function() {
		if ($(this).val() == 'United States') {
			$('#SupportForm').find('#state').parents('div:first').show();
		} else {
			$('#SupportForm').find('#state').parents('div:first').hide();
		}
	});
	$('#SupportForm').validate( { errorElement: 'span' } );
	
	// Support Form validation
	$('#CampaignLandingForm').find('#country').change(function() {
		if ($(this).val() == 'United States') {
			$('#CampaignLandingForm').find('#state').show();
		} else {
			$('#CampaignLandingForm').find('#state').hide();		
		}
	}).each(function() {
		if ($(this).val() == 'United States') {
			$('#CampaignLandingForm').find('#state').show();
		} else {
			$('#CampaignLandingForm').find('#state').hide();
		}
	});
	$('#CampaignLandingForm').validate( { errorElement: 'span' } );
	
	// WhitepaperForm validation
	$('#WhitepaperForm').find('#country').change(function() {
		// alert("changed");
		if ($(this).val() == 'United States') {
			$('#WhitepaperForm').find('#state').parents('div:first').show();
		} else {
			$('#WhitepaperForm').find('#state').parents('div:first').hide();		
		}
	}).each(function() {
		if ($(this).val() == 'United States') {
			$('#WhitepaperForm').find('#state').parents('div:first').show();
		} else {
			$('#WhitepaperForm').find('#state').parents('div:first').hide();
		}
	});
	$('#WhitepaperForm').validate( { errorElement: 'span' } );
});
