// 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');
	DD_belatedPNG.fix('#Content table.comparison span.checkmark, #Content table.comparison span.xmark');
	DD_belatedPNG.fix('#Content .resourceItem p.image a img');
	DD_belatedPNG.fix('#NavigationPrimary li.over li a, #NavigationPrimary li li a');
	DD_belatedPNG.fix('#FreeTrial, #CloudResourceKit');
}

/* 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 HomeMastCarousel = {
    carousel: null,
    paused: false,
    clicked: 0,
    init: function() {
        $('#HomeMastCarousel').each(function(i) {
            $(this).find('li.hideOnLoad').removeClass('hideOnLoad');
            $(this).jcarousel({
                auto: 6,
                wrap: 'circular',
                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);
        });
        $('body.home #Mast').live('mouseover', HomeMastCarousel.mastMouseover)
                            .live('mouseout', HomeMastCarousel.mastMouseout);
    },
    itemVisibleInCallback: function(c, el, i, state) {
        $('ul.carouselNav').find('li.active').removeClass('active').end().find('li:eq(' + (i - 1) + ')').addClass('active');
    },
    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 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 - Causing problems with new CMS
		//$('#Wrapper a[href^=https://]').not($('a.noPopup')).popupwindow(); // Secure HTTP connection links - Causing problems with new CMS
		$('#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 != '';
		} else if ($(element).parents('form:first').find('select[name=country]').val() == 'Canada') {
			return value != '';
		}
		return true;
	},
	"Please select a state/province"
);

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");

var CountryStateField = {
	hiddenOptions: null,
	formList: null,
	interval: null,
	lastCountry: null,
	init: function() {
		CountryStateField.formList = $('#HowToBuyForm,#ContactUsForm,#TCOCalculatorForm,#ResourceKitForm,#SupportForm,#CampaignLandingForm,#WhitepaperForm');
		CountryStateField.formList
			.each(function() {
				$(this).find('#country').change(CountryStateField.change);
			})
			.validate( { errorElement: 'span' } );
		
		if (CountryStateField.interval == null) {
			CountryStateField.checkForChange();
			CountryStateField.interval = window.setInterval(CountryStateField.checkForChange, 1000);
		}
	},
	change: function(e) {
		CountryStateField.handleChange($(this));
	},
	checkForChange: function() {
		if (CountryStateField.formList == null)
			CountryStateField.init();
			
		CountryStateField.formList.each(function() {
			var $country = $(this).find('#country');
			CountryStateField.handleChange($country);
		});
	},
	handleChange: function($country) {
		if (CountryStateField.lastCountry != $country.val()) {
			var $$ = $country.parents('form:first');
			var $state = $$.find('#state');
			var $state_label = $$.find('#stateLabel');
			$state.append(CountryStateField.hiddenOptions);
			
			var $div = $state.parents('div:first');
			if ($country.val() == 'United States') {
				if ($div.hasClass('channel')) {
					$state.show();
					$state_label.show();
				}
				else
					$div.show();
				CountryStateField.hiddenOptions = $state.find('option.CA').detach();
			} else if ($country.val() == 'Canada') {
				if ($div.hasClass('channel')) {
					$state.show();
					$state_label.show();
				}
				else
					$div.show();
				CountryStateField.hiddenOptions = $state.find('option.US').detach();
			} else {
				if ($div.hasClass('channel')) {
					$state.hide();
					$state_label.hide();
				}
				else
					$div.hide();
				CountryStateField.hiddenOptions = $state.find('option.US, option.CA').detach();
				$$.find('#state').val('');
			}
			CountryStateField.lastCountry = $country.val();
		}
	}
};

$(document).ready(CountryStateField.init);

