// helper for tweets. we really need to modularize this stuff :)
Date.prototype.toRelativeTime = function(now_threshold) {
  var delta = new Date() - this;

  if (delta <= 0) {
    return 'Just now';
  }

  var units = null,
     conversions = {
    millisecond: 1, // ms    -> ms
    second: 1000,   // ms    -> sec
    minute: 60,     // sec   -> min
    hour:   60,     // min   -> hour
    day:    24,     // hour  -> day
    month:  30,     // day   -> month (roughly)
    year:   12      // month -> year
  };

  for (var key in conversions) {
    if (delta < conversions[key]) {
      break;
    } else {
      units = key; // keeps track of the selected key over the iteration
      delta = delta / conversions[key];
    }
  }

  delta = Math.floor(delta);
  if (delta !== 1) { units += "s"; }
  return [delta, units, "ago"].join(" ");
};

var NLTour,
	playTourVideoOnLoad = null;

jQuery(document).ready(function($) {
	
	// add OS class to html tag
	$('html').addClass('browser-os-'+ (
		navigator.userAgent.match(/Macintosh/) ? 'macos' :
		navigator.userAgent.match(/Windows/) ? 'windows' :
		navigator.userAgent.match(/Linux/) ? 'linux' :
		'unknown')
	);

	// hover and click on nav links
	$('nav li')
	
		.click(function() {
			var innerLink = $(this).find('a:first');
			
			if (innerLink.length) {
				if (innerLink.attr('href') && innerLink.attr('href') != '#' && innerLink.attr('href').length) 
					window.location.href = innerLink.attr('href');
			}
			
			if ($(this).is('.facebook, .twitter, .linkedin')) {
				_gaq.push(['_trackPageview', '/exit/' + $(this).text().toLowerCase()]);
			}
		})

		.hover( function() {
			$(this).addClass('hover');
		}, function() {
			$(this).removeClass('hover');
		});
		
	// rotate testimonials
	if ($('#testimonial').length) {
		window.setInterval(function() {
			var current = $('#testimonial div:visible'),
				next = (current.next().length) 
					? current.next()
					: current.siblings().first();

			current.fadeOut();
			next.fadeIn();
		}, 6000);
	}
	
	// if we're showing tweets somewhere, load the twitter widget async
	var tweetContainer = $('ol.tweets'),
		numTweets = 4;
	if (tweetContainer.length) {
		$.getJSON('http://api.twitter.com/1/statuses/user_timeline.json?trim_user=true&count=' + numTweets + '&screen_name=nutshell&callback=?', function(data) {
			$.each(data, function(i, tweet) {
				var text = tweet.text,
					date = new Date(Date.parse(tweet.created_at.replace(/^([a-z]{3})( [a-z]{3} \d\d?)(.*)( \d{4})$/i, '$1,$2$4$3'))).toRelativeTime();
					
				text = text
				.replace(/((http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?)/gi, '<a href="$1" class="link-url">$1</a>')
				.replace(/[\@]+([A-Za-z0-9-_]+)/gi, '<a href="http://twitter.com/$1" class="link-username">@$1</a>');
				
				tweetContainer.append('<li><p>' + text + '</p><span>' + date + '</span></li>');
			});
		});
	}
		
	var Signup = {
		handleFieldValidation: function(field, response) {
			if (!response) return;
			
			field.removeClass('state-invalid state-valid');
			
			
			if (response.isValid) {
				if (field.find('input').val().length == 0) return true;
				field.addClass('state-valid');
			} else {
				field.addClass('state-invalid');
				var invalidMessage = field.find('aside.invalid'),
					messageText = response.message || invalidMessage.data('message');
				
				invalidMessage.html(messageText);
				
				_gaq.push(['_trackEvent', 'SignupForm', 'InvalidField', messageText]);
			}
		}
	};
	
	$('#signup form.signup').submit(function(event) {
		var form = $(this);
		
		if (form.is('.state-loading')) return;
		form.addClass('state-loading');
		
		event.preventDefault();
		
		_gaq.push(['_trackEvent', 'SignupForm', 'SubmitAttempt']);
		
		$.ajax({
			url: '/signup/submit.json',
			type: 'POST',
			data: form.serializeArray(),
			success: function(response) {
				form.removeClass('state-loading');
				
				if (response.isRedirectResult) {
					window.location = response.redirectUrl;
					return;
				} else { // assume validation
					$.each(response, function(key, value) {
						_gaq.push(['_trackEvent', 'SignupForm', 'SubmitFailedValidation']);
						Signup.handleFieldValidation(form.find('input[name=' + key + ']').closest('dd'), value);
					});
				}
			},
			error: function() {
				form.removeClass('state-loading');
				
				_gaq.push(['_trackEvent', 'SignupForm', 'SubmitFailedCompletely']);
				
				// @TODO present in UI
				alert('There was a problem creating your account');
			}
		});
	});
	
	$('#signup form.signup input')
	
		.focus(function() {
			$(this).closest('dd').addClass('state-focused');
		})
		.blur(function() {
		var input = $(this),
			container = input.closest('dd');
			
		container.removeClass('state-focused');
		
		$.ajax({
			url: '/signup/validate-field.json',
			data: {
				field: input.attr('name'),
				value: input.val()
			},
			success: function(result) {
				Signup.handleFieldValidation(container, result);
			}
		});
	});
	
	$('#login form.login .input-username').focus();
	
	$('#login form.login').submit(function(event, srsly) {
		if (srsly) return true; // we're calling ourself, so go ahead and submit, otherwise we're intercepting browser
		
		var form = $(this);
		event.preventDefault();
		
		$.ajax({
			url: '/login/get-url.json',
			data: {
				username: form.find('input[name=username]').val()
			},
			success: function(response) {
				form.attr('action', response.url)
					.trigger('submit', true );
			}, error: function(xhr, errorText, errorThrown) {
				var response,
					message = 'There was a problem connecting to the login server';
				try {
					response = $.parseJSON(xhr.responseText);
				} catch(e) {
					response = null;
				}
				
				if (response.code) { // from Ops_Api_Exception
					switch (response.code) {
						case 1000:
							message = 'Could not find an account for that domain';
							break;
						case 1002:
							message = 'Invalid username';
							break;
					}
				}
				
				form.find('.errors').text(message);
			}
		});
	});
	
	// demo login
	$('.action-startdemo').click(function(event) {
		event.preventDefault();
		
		_gaq.push(['_trackPageview', '/demo/launch']);
		
		$('form#demo-login').submit();
	});
	
	// click a specific tour video based on anchor
	if ($('body#tour').length) {
		if (window.location.hash && window.location.hash.length) {
			playTourVideoOnLoad = window.location.hash.substr(1);
		}
	}
	
	NLTour = {
		videoWasClicked: function(event) {
			event.preventDefault();
			var li = $(this).closest('li'),
				ribbon = li.closest('.swoopy-ribbon-list').siblings('.swoopy-ribbon'),
				videoName = $(this).data('video');

			li.addClass('state-selected').siblings().removeClass('state-selected');
			ribbon.css({ top: li.position().top });
			
			// now the video
			var video = $('#video video').get(0);
			
			// if non-ie
			if (video && typeof video.pause != 'undefined') video.pause();
			
			$('#video .video-container')
				.html(NLVideo.getVideoTagForVideo(videoName));
				
			var player = NLVideo.createFromVideoTag.apply($('#video video'));
		}
	};
	
	require(['/js/nlvideo.js', '/mediaelement/mediaelement-and-player.js', '/js/facebox.js'], function() { NLVideo.onLoad(); });
	
	if ($('#moreinfo').length) {
		require(['/js/jquery.rating.js']);
	}
	
	if ($('#support').length) {
		require(['/jquery-ui/jquery-ui-1.8.11.custom.min.js'], function() {
			$('#kb-autocomplete').autocomplete({
				source: function(acRequest, acResponse) {
					$.ajax({
						url: '/solr/select',
						dataType: 'json',
						data: {
							wt: 'json',
							qt: 'kb',
							q: acRequest.term
						},
						success: function(solrResponse) {
							var formattedResponse = [];
							if (solrResponse.response && solrResponse.response.docs) {
								$.each(solrResponse.response.docs, function(i, doc) {
									var content;
									if (solrResponse.highlighting 
										&& solrResponse.highlighting[doc.id]
										&& solrResponse.highlighting[doc.id].text) {
										content = solrResponse.highlighting[doc.id].text;
									} else {
										content = doc.summary;
									}
									
									formattedResponse.push({
										label: doc.title,
										url: doc.url,
										content: content
									});
								});
							}
							
							// add blank item
							if (formattedResponse.length == 0) {
								formattedResponse.push({
									label: 'No results found',
									url: null,
									content: null
								})
							}
							
							acResponse(formattedResponse);
							_gaq.push(['_trackEvent', 'SupportForm', 'Searched', acRequest.term]);
						},
						error: function() {
							acResponse();
						}
					});
				},
				select: function(event, ui) {
					if (ui.item.url) {
						window.location.href = ui.item.url;
					} else {
						NutshellSupportWidget.open();
					}
					return false;
				},
				focus: function(event, ui) {
					return false; // prevent arrows from changing input text
				}
			}).data('autocomplete')._renderItem = function( ul, item ) {
				var li = $("<li></li>")
					.data( "item.autocomplete", item );
				
				if (item.url) {
					li.html("<a><span class='title'>" + item.label + "</span><br> \
						<span class='excerpt'>" + item.content  + "</span></a>" )
				} else { // empty result item
					li.html("<a><span class='empty'>" + item.label + "</span><br> \
						<span class='excerpt'>Contact us for additional support</span></a>")
				}
					
				li.appendTo( ul );
			};
		});
	}
	
	$('a.behavior-support').click(function(event) {
		event.preventDefault();
		NutshellSupportWidget.open();
	});

	
	// unsubscribe
	$('a.action-unsubscribe').live('click', function(event){
		event.preventDefault();
		var email = window.location.href.slice(window.location.href.indexOf('email=') + 6);
		window.location.href = '/email/unsubscribe?email=' + email;
	});
	
	require(['/js/placeholder.js'], function() {
		$('input[placeholder],textarea[placeholder]').placeholder();
	});
	
	// hack to remove unnecessary member list from renderers in API docs
	if ($('body').hasClass('doxygen')) {
		if($('.headertitle *:contains("Render_Model")').length == 1) {
			$('table.memberdecls').hide();
		}
	}

	if ($('#google-steps').length) {
		require(['/js/google-setup.js'], function() {GoogleSetup.go();});
	}
});

