window.marketo = window.marketo || {};

// Misc functions, utilities
marketo = {
	log: function(){
		this.history = this.history || [];
		this.history.push(arguments);
		if(window.console){
			console.log( Array.prototype.slice.call(arguments) );
		}
	}
};

// Run on $.ready()
marketo.init = {
	foucFix: function () {
		$('.fouc-fix').removeClass('fouc-fix');
	},
	labels: function () {
		$('label').each(function() {
			if(!$(this).hasClass('notinfield')) {
				$(this).inFieldLabels();
			}
		});
	},
	vAlign: function () {
		// $('.home .button-play').vAlign();
	},
	dialog: function () {
		$('.video-full').add('.back.video-cta').hide();
		$('.icon-large-video').click(function(){
			$('.video-group').dialog(
				{
					dialogClass: 'shadow-light',
					width: '712',
					title: 'Customer<br /><span class="pull-back">Testimonials</span>',
					closeText: 'X',
					modal: true,
					beforeClose: function() {
						setTimeout("window.location.hash = '';",50);
					},
					open: function() {
						window.location.hash = 'testimonials';
						mktoMunchkinFunction('clickLink', {
							href: window.location.href
						});
					}
				}
			);
		});
		// close video dialog on click outside of dialog container
		var mouse_inside = false;
		$('body').mouseup(function() {
			if(!mouse_inside && window.location.hash != '') {
				$('a.return').eq(0).click();
				$(".video-group").dialog("close");
			}
		});
		$('body').delegate('.ui-dialog', 'mouseover mouseout', function(event) {
			mouse_inside = (event.type == 'mouseover');
		});
	},
	qtip: function () {
		// Defaults for homepage icon popovers
		$.fn.qtip.styles.theme1 = {
			width: {'max': '500'},
			padding: '0  35px 15px',
			color: '#ffffff'
		};
		popoverDefaults =
		{
			position: {
				target: $('#qtip-blanket'),
				corner: 'center',
				adjust: {
					y: 50,
					x: 0
				}
			},
			style: {
				name: 'theme1',
				background: '#5a53a3',
				opacity: .95,
				title: {
					background: '#5a53a3',
					opacity: .95
				}
			},
			show: {
				delay: 0,
				when: {event: 'click'}
			},
			hide: 'unfocus'
		};
		if ($('.icon-large-revenue').length) {
			$('.icon-large-revenue').qtip($.extend(popoverDefaults,
				{
					content: {
						text: 'Grow revenue faster by expanding lead flow, optimizing sales and marketing investments and improving productivity with Revenue Performance Management (RPM). Combining marketing automation, lead nurturing and more, it’s a must-have solution with amazing bottom-line impact.<p class="more"><a href="/about/revenue-performance-management/revenue-quotient.php">Learn More</a></p>',
						title: {
							text:'Achieve <br /><span class="pull-back">Success!</span>',
							button: ''
						}
					}
				})
			);
			$('.icon-large-customers').qtip($.extend(popoverDefaults,
				{
					content: {
						text: 'Learn how over 1,600 of the world’s most innovative and successful organizations in more than 30 countries rely on Marketo for their marketing automation and lead management needs.<p class="more"><a href="/customers/customers-a-z/">Learn More</a></p>',
						title: {
							text:'A World of <br /><span class="pull-back">Success</span>',
							button: ''
						}
					}
				})
			);
			$('.icon-large-impact').qtip($.extend(popoverDefaults,
				{
					content: {
						text: 'Looking to increase marketing accountability, justify your marketing budget, and demonstrate marketing’s impact on revenue? You’ve come to the right place. <p class="more"><a href="/b2b-marketing-resources/category/best-practices/marketing-roi">Learn More</a></p>',
						title: {
							text:'Resources for <br /><span class="pull-back">Success</span>',
							button: ''
						}
					}
				})
			);
			$('.icon-large-story').qtip($.extend(popoverDefaults,
				{
					content: {
						text: 'From humble beginnings in 2006 to recently being included on Forbes Magazine’s “America’s Most Promising Companies” list, learn more about what makes Marketo unique in its quest to change the way marketing and sales teams collaborate throughout the revenue cycle.<p class="more"><a href="/about">Learn More</a></p>',
						title: {
							text:'Our <br /><span class="pull-back">Story</span>',
							button: ''
						}
					}
				})
			);
			$('.icon-large-roi').qtip($.extend(popoverDefaults,
				{
					content: {
						text: 'Take our ROI calculator for a spin and see what marketing automation and revenue performance management means for you. See how you can identify the costs and revenue associated with your marketing programs and calculate the net business impact.<p class="more"><a href="/marketing-automation-roi-calculator/">Learn More</a></p>',
						title: {
							text:'Quantify Your <br /><span class="pull-back">Investment</span>',
							button: ''
						}
					}
				})
			);
			$('.icon-large-trial').qtip($.extend(popoverDefaults,
				{
					style: {
						name: 'theme1',
						background: '#00a5d9',
						opacity: .95,
						title: {
							background: '#00a5d9',
							opacity: .95
						}
					},
					content: {
						text: 'Sign up today to test drive the industry’s leading marketing automation and revenue performance management platform. No hassles, obligations or high-pressure sales tactics—just an easy way for you to see how Marketo can empower your sales and marketing teams to shorten your revenue cycle, demonstrate marketing ROI, and ignite explosive revenue growth.<p class="more"><a href="/freetrial.php">Learn More</a></p>',
						title: {
							text:'Test <br /><span class="pull-back">Drive</span>',
							button: ''
						}
					}
				})
			);
			$('.icon-large-demo').qtip($.extend(popoverDefaults,
				{
					style: {
						name: 'theme1',
						background: '#00a5d9',
						opacity: .95,
						title: {
							background: '#00a5d9',
							opacity: .95
						}
					},
					content: {
						text: 'Take just a few minutes and discover why Marketo is the must-have marketing automation solution with an amazing bottom-line impact.<p class="more"><a href="http://pages2.marketo.com/demo.html">Learn More</a></p>',
						title: {
							text:'Marketo In <br /><span class="pull-back">Action</span>',
							button: ''
						}
					}
				})
			);
			$('.icon-large-pricing').qtip($.extend(popoverDefaults,
				{
					style: {
						name: 'theme1',
						background: '#00a5d9',
						opacity: .95,
						title: {
							background: '#00a5d9',
							opacity: .95
						}
					},
					content: {
						text: 'From Small Business to Enterprise, check out our scalable pricing that strives to make the benefits of marketing automation and Revenue Performance Management (RPM) accessible to you, regardless of your business size.<p class="more"><a href="/b2b-marketing-software/marketing-automation-pricing.php">Learn More</a></p>',
						title: {
							text:'&nbsp;<br /><span class="pull-back">Pricing</span>',
							button: ''
						}
					}
				})
			);
			$('.icon-large-awards').qtip($.extend(popoverDefaults,
				{
					style: {
						name: 'theme1',
						background: '#00a5d9',
						opacity: .95,
						title: {
							background: '#00a5d9',
							opacity: .95
						}
					},
					content: {
						text: 'Excuse us while we blow our own horn, but here you can learn more about the many awards in which Marketo has been honored—a genuine  tribute to the creativity and drive of Marketo&#39s employees, and our industry-leading solutions.<p class="more"><a href="/about/news/awards">Learn More</a></p>',
						title: {
							text:'Awards &amp; <br /><span class="pull-back">Recognition</span>',
							button: ''
						}
					}
				})
			);

			$('.icon-large-quotes').qtip($.extend(popoverDefaults,
				{
					content: {
						text: '<div class="clearfix"><img class="left" style="margin-right: 10px;" src="_media/thumb_quote_ben_lamorte.png" width="85" height="115" alt="Thumb Quote Ben Lamorte">"With Marketo, we now generate five times the number of leads at half the cost."<br />BEN LAMORTE<br />Vice President of Sales<br />Alight Planning</div><p class="more"><a href="/customers/index.php">More Success</a></p>',
						title: {
							text:'Customer <br /><span class="pull-back">Quotes</span>',
							button: ''
						}
					}
				})
			);
			$('.icon-large-guide').qtip($.extend(popoverDefaults,
				{
					style: {
						name: 'theme1',
						background: '#00a5d9',
						opacity: .95,
						title: {
							background: '#00a5d9',
							opacity: .95
						}
					},
					content: {
						text: '<div class="clearfix"><img class="left" style="margin-right: 10px;" src="/_media/thumb_definitive_guide.png" width="85" height="115" alt="Thumb Definitive Guide">This groundbreaking 70 page workbook will teach you how to proactively speak the CXO language of forecasting and reporting. Earn marketing a place at the revenue table by using solid metrics that work.</div><p class="more"><a href="http://pages2.marketo.com/dg2-marketing-metrics.html">Learn More</a></p>',
						title: {
							text:'Speak the<br /><span class="pull-back">language!</span>',
							button: ''
						}
					}
				})
			);
			$('.icon-large-news').qtip($.extend(popoverDefaults,
				{
					style: {
						name: 'theme1',
						background: '#00a5d9',
						opacity: .95,
						title: {
							background: '#00a5d9',
							opacity: .95
						}
					},
					content: {
						text: $('.hidden-news').html()+'<p class="more"><a href="/about/news/">More News</a></p>',
						title: {
							text:'Marketo<br /><span class="pull-back">News</span>',
							button: ''
						}
					}
				})
			);
		}

		// Defaults for social media popovers
		$.fn.qtip.styles.theme2 = {
			width: {'max': '500'},
			padding: '0  35px 15px',
			color: '#58595b',
			background: '#ffffff',
			title: {
				background: '#ffffff',
				color: '#58595b'
			}
		};
		popoverWhite =
		{
			style: {
				name: 'theme2',
				opacity: 1
			},
			show: 'click',
			solo: true,
			hide: 'unfocus',
			// api call to onShow to fix bugs in plugin (not changing opacity and not hiding other showing tooltips)
			api: {
				onShow: function() {
					var that = this.id;
					$(this).css({opacity: 1});
					$('.qtip').each(function() {
						if($(this).attr('qtip') != that) {
							$(this).qtip('hide');
						} else {
							$(this).css({opacity: 1});
						}
					});
				}
			}
		};
		$('.sidebar .facebook').qtip($.extend(popoverWhite,
			{
				content: {
					text: $('.follow-facebook'),
					title: {
						text:'<span class="pull-back">Like</span><br />Marketo',
						button: ''
					}
				},
				position: {
				      corner: {
				         target: 'bottomRight',
				         tooltip: 'topRight'
				      },
				      adjust: {
						x: 114
				      }
				}
			})
		);
		$('.sidebar .twitter').qtip($.extend(popoverWhite,
			{
				content: {
					text: $('.follow-twitter'),
					title: {
						text:'<span class="pull-back">Follow</span><br />Marketo',
						button: ''
					}
				},
				position: {
				      corner: {
						 target: 'bottomRight',
						 tooltip: 'topRight'
				      },
				      adjust: {
						x: 76
				      }
				}
			})
		);
		$('.sidebar .linkedin').qtip($.extend(popoverWhite,
			{
				content: {
					text: $('.follow-linkedin'),
					title: {
						text:'<span class="pull-back">Follow</span><br />Marketo',
						button: ''
					}
				},
				position: {
					  corner: {
						 target: 'bottomRight',
						 tooltip: 'topRight'
					  },
					  adjust: {
						x: 38
					  }
				}
			})
		);
		$('.sidebar .googleplus').qtip($.extend(popoverWhite,
			{
				content: {
					text: $('.follow-googleplus'),
					title: {
						text:'<span class="pull-back">+1</span><br />Marketo',
						button: ''
					}
				},
				position: {
					  corner: {
						 target: 'bottomRight',
						 tooltip: 'topRight'
					  },
					  adjust: {
						x: 0
					  }
				}
			})
		);
	},
	tabs: function () {
		var onHome = $('body').hasClass('home');
		$('.tabs').tabs();
		$('.footer-tabs').tabs({
			//selected: $('.home').length > 0 ? 0 : -1,
			selected: -1,
			collapsible: true,
			show: function() {
				if (!onHome)
					window.scrollTo(0, document.body.scrollHeight);
			}
		});
		$('.footer-close').click(function(){
			$('.footer-tabs').tabs({
				selected: -1
			});
		});
	},
	lightbox: function () {
		$(".lightbox").colorbox({opacity: 0});
		$(".lightbox-product").colorbox({
			opacity: 0
		});
		$(".lightbox-presentation").colorbox({
			opacity: 0,
			iframe: true,
			innerWidth:560,
			innerHeight:350
		});

	},
	videos: function () {
		// Homepage Video thumbnails

		$('.home a.video').click(function(){
			$('.video-full').add('.back.video-cta').show();
			var $this = $(this);

			//make it shareable...
			window.location.hash = $this.attr('href');
			//Track what video has been clicked in marketo
			mktoMunchkinFunction('clickLink', {
			    href: window.location.href
			});

			// Grab video ID and generate youtube url
			var embedCode = '<div class="video-holder">'
					  +		'<iframe width="640" height="360" src="http://www.youtube.com/embed/'+$this.attr('rel')+'?rel=0&amp;controls=1&amp;modestbranding=1&amp;autoplay=1&amp;autohide=1" frameborder="0" allowfullscreen></iframe>'
					  + '</div>';
			$('.video-full').prepend(embedCode);
			// Toggle between thumbnails and full video
			$('.thumbnails').fadeOut('100');
			$('a.ui-dialog-titlebar-close').add('a.return').click(function(){
				window.location.hash = 'testimonials';
				$('.video-full').add('.back.video-cta').hide();
				$('.video-holder').remove();
				$('.thumbnails').fadeIn('100');
			});
			return false;
		});


		// Video testimonials
		window.$testimonialTabs = $('#testimonial-content').tabs();
		if(window.location.hash) {
			var $SelectedVideo = $('a.video[data-customer='+window.location.hash.substr(1)+']');
			if ($SelectedVideo.length) {
				selectVideoTestimonial($SelectedVideo.attr('id').replace('testimonial-nav-', ''));
			} else {
				window.location.hash = '';
			}
		}
		$('.page-video-testimonials a.video').click(function() {
			var $this = $(this);

			window.location.hash = $this.data('customer');

			selectVideoTestimonial($this.attr('id').replace('testimonial-nav-', ''));

			//Track what video has been clicked in marketo
			mktoMunchkinFunction('clickLink', {
				href: window.location.href
			});
			return false;
		});
	},
	tables: function () {
		$("table.customers-a-z tr td").eq(0).css("font-family", "sans-serif");
		$("table.stripes tr:even").addClass("even");
	},
	resource_tabs: function () {
		// Resources Blog dropdown change order of contents display
		$selectTabs = $('#select-tabs');
		$selectTabs.change(function(){
			selectValue = $(this).val();
			$('.sorted','.subcategory-tabs').hide();
			$('div.sorted.'+selectValue,'.subcategory-tabs').show();
		});
	},
	mainNav: function () {
		var nav_open_check = false;
		// If homepage, push absolutely positioned content down by same amount
		if ($('body').hasClass('home')) {
			var subnavHeight = '350px';
		}
		$('.main-nav a').click(function(event){
			event.preventDefault();
			$('.ui-dialog').hide(); // Close video popovers if they're up

			var $this = $(this);
			var content = $('.nav-content.' + $this.attr('id'));
			var links   = $('.nav-content.' + $this.attr('id') + ' .main-nav-links');
			var sidebar = $('.nav-content.' + $this.attr('id') + ' .sidebar');

			if ($('body').hasClass('nav-open') && !$this.hasClass('open')) {
				$('.nav-content').addClass('hide').removeAttr('style');
				content.removeClass('hide');
				links.show('slide', {direction: 'right'}, nav_push_duration);
				sidebar.removeClass('hide');
			} else {
				if ($this.hasClass('open')) {
					content.slideUp(nav_push_duration);
					$('body').removeClass('nav-open');
					if ($('body').hasClass('home')) {
						$('#parts').animate({top:'-='+subnavHeight},nav_push_duration);
						$('#footer').animate({bottom:'+='+subnavHeight},nav_push_duration);
						//$('body').css('padding-bottom', '-='+subnavHeight);
						$('#home-sidebar').css('top', 370);
					}
					nav_open_check = false;
				} else {
					nav_open_check = true;
					content.slideDown(nav_push_duration);
					content.removeClass('hide');
					sidebar.removeClass('hide');
					$('body').addClass('nav-open');
					if ($('body').hasClass('home')) {
						$('#parts').animate({top:'+='+subnavHeight}, nav_push_duration);
						$('#footer').animate({bottom:'-='+subnavHeight}, nav_push_duration);
						//$('body').css('padding-bottom', '+='+subnavHeight);
						$('#home-sidebar').css('top', 625);
					}
				}
			}

			if ($this.hasClass('open')) {
				$this.removeClass('open');
			} else {
				$this.addClass('open');
				$('.open').not(this).removeClass('open');
			}
		});

		var mouse_inside_dropdown = false;

		$('body').mouseup(function() {
			if(! mouse_inside_dropdown && nav_open_check) {
				navClose(subnavHeight);
				nav_open_check = false;
			}
		});
		var timer;
		$('.main-nav li a').hover(function() {
			mouse_inside_dropdown = true;
			clearTimeout(timer);
		}, function() {
			mouse_inside_dropdown = false;
			if(nav_open_check) {
				timer = setTimeout(function() {
					if (nav_open_check) navClose(subnavHeight);
					nav_open_check = false;
				}, 1000);
			}
		});
		$('.nav-content-container').hover(function() {
			mouse_inside_dropdown = true;
			clearTimeout(timer);
		}, function() {
			mouse_inside_dropdown = false;
			if(nav_open_check) {
				timer = setTimeout(function() {
					if (nav_open_check) navClose(subnavHeight);
					nav_open_check = false;
				}, 1000);
			}
		});

		$('.nav-close').click(function(){
			navClose(subnavHeight);
			nav_open_check = false;
		});
	},
    carousel: function() {
		$('.video-thumb-slider').jCarouselLite({
			btnNext: '.video-slider-next',
			btnPrev: '.video-slider-prev',
			visible: 2
		});
	},
	tweet: function() {
		$('.twitter-box-phil').tweet({
			username : "philf1217",
			count : 1,
			template : '<p>{tweet_text}</p> <span>{tweet_relative_time} | <a href="{reply_url}">Reply</a></span>'
		});
	},
	tweet2: function() {
		$('.twitter-box-jon').tweet({
			username : "jonmiller2",
			count : 1,
			template : '<p>{tweet_text}</p> <span>{tweet_relative_time} | <a href="{reply_url}">Reply</a></span>'
		});
	},
	tweet_lori: function() {
		$('.twitter-box-lori').tweet({
			username : "lbshepard",
			count : 1,
			template : '<p>{tweet_text}</p> <span>{tweet_relative_time} | <a href="{reply_url}">Reply</a></span>'
		});
	},
	tweet_fergus: function() {
		$('.twitter-box-fergus').tweet({
			username : "fgloster",
			count : 1,
			template : '<p>{tweet_text}</p> <span>{tweet_relative_time} | <a href="{reply_url}">Reply</a></span>'
		});
	},
	targetblank: function() {
//		var link = $('.sub-nav-links li a span');
//		link.each(function() {
//			if($(this).text() == "Careers" || $(this).text() == "Join the Marketo Alliance" || $(this).text() == "Small Business Pricing") {
//				$(this).closest('a').attr({'target' : '_blank'});
//			}
//		});
	},
	share_count: function() {
		$('.js-share').each(function () {
			var url = $(this).data('share-url');
			var parent = $(this);

			$.get('/api/share/count?url=' + encodeURIComponent(url), function (data) {
				$.each(data, function (key, value) {
					$('.js-share-' + key, parent).text(value);
				});
			});
		});
	},
	promo_display: function() {
		var promos = $('.resource-promo');
		var promos = $(promos);
		var r      = Math.floor(Math.random() * promos.length);
		promos.slice(r, r+1).removeClass('hidden');
	},
	companySort: function(term) {
		if(!term) return;
		var ele = $('table.customers-a-z tbody tr');
		ele.show();
		ele.removeClass('even');
		term = $('select.company-size').val();
		if(term != 'none') {
			ele.each(function(){
				var thing = $(this).children('.customer-size-ele').text();
				if(thing.toLowerCase() != term.toLowerCase()) {
					$(this).hide();
				}
			});
		}
		term = $('select.industry').val();
		if(term != 'none') {
			ele.each(function(){
				var thing = $(this).children('.industry-ele').text();
				if(thing.toLowerCase() != term.toLowerCase()) {
					$(this).hide();
				}
			});
		}
		ele = ele.filter(':visible');
		ele.each(function(index) {
			if(index === 0 || index % 2 === 0) {
				$(this).addClass('even');
			}
		});
	},
	companySize: function() {
		$('select.company-size').change(function(){
			var type = $(this).val();
			marketo.init.companySort(true);
		});
	},
	companyIndustry: function() {
		$('select.industry').change(function(){
			var type = $(this).val();
			marketo.init.companySort(true);
		});
	},
	industryListNav: function() {
		var industryType = $.getUrlVars()['industryType'];
		if(industryType) {
			industryType = industryType.replace(/%20/g, ' ').replace(/_/g, '&'); //replace %20 with spaces and underscores with & from the parameters
			$('select.industry').val(industryType.toLowerCase());
			marketo.init.companySort('industry', industryType);
		}
	}
};

$(document).ready(function() {
	$.each(marketo.init,
		function(i,item) {
			item();
		}
	);
});

var nav_push_duration = 400;

function navClose(subnavHeight) {
	var id = $('.open').attr('id');
	$('body').removeClass('nav-open');
	$('.open').removeClass('open');
	$('.nav-content.'+id).slideUp('fast');
	if ($('body').hasClass('home')) {
		$('#parts').animate({top:'-='+subnavHeight},nav_push_duration);
		$('#footer').animate({bottom:'+='+subnavHeight},nav_push_duration);
		$('body').css('padding-bottom','-='+subnavHeight);
		$('#home-sidebar').css('top', 370);
	}
	return false;
}
function selectVideoTestimonial(ID) {
	if (!ID) {
		alert('Invalid Video ID');
		return false;
	}

	var $testimonialNav = $('#testimonial-nav-'+ID),
		$testimonial = $('#testimonial-'+ID);
	if (!$testimonial.length || !$testimonialNav.length) {
		alert('Cannot find the video you\'re looking for.');
		return false;
	}

	var video = $testimonialNav.attr('rel');
	if (!video) {
		alert('Video is missing.');
		return false;
	}

	$('.cust-vid-cont').empty();
	window.$testimonialTabs.tabs('select', ID);

	// generate embed code
	var embedCode = '<div class="video-holder">';
	switch (video) {
		case 'bronto': case 'cvsdude': case 'echalk': case 'idology': case 'shipserv': case 'strongmail': case 'targusinfo': case 'vendavo': case 'zuora':
			embedCode += '<div class="cust-vid-cont"><iframe width="560" height="350" src="'+video+'/video.html" frameborder="0" allowfullscreen autoplay></iframe></div>';
			break;
		default:
			embedCode += '<div class="cust-vid-cont"><iframe width="519" height="350" src="http://www.youtube.com/embed/'+video+'?rel=0&amp;controls=1&amp;modestbranding=1&amp;autoplay=1&amp;autohide=1" frameborder="0" allowfullscreen></iframe></div>';
	}
	embedCode += '</div>';
	$('.video-holder').remove();
	$testimonial.prepend(embedCode);
	window.scrollTo(0, 0);
	return true;
}
function trim(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}

