
/**
* Site behaviors and plugins, loaded site-wide (multiple times).
*
* @category	Javascript
* @author   Eric Ingram <eric@trulynetworks.com>
*/

// On ready...
$(document).ready(function ()
{
	/**
	* Fix z-index issue on IE7.
	*/
	if ($.browser.msie && $.browser.version.substr(0,1) == 7)
	{
		$('div.navigation').css('zIndex', 1000);
	}

	/**
	* Navigation functionality.
	*/
	var tabTimersDown = {};
	var tabTimersUp = {};
	var id;

	$('dl.nav-main dd.tab').mouseenter(function ()
	{
		id = $(this).attr('id');
		clearTimeout(tabTimersUp[id]);
		clearTimeout(tabTimersDown[id]);
		tabTimersDown[id] = setTimeout("$('#"+id+"').addClass('on').find('.shadow').stop(true, true).slideDown('fast');", 100);
	});
	$('dl.nav-main dd.tab').mouseleave(function ()
	{
		id = $(this).attr('id');
		clearTimeout(tabTimersUp[id]);
		clearTimeout(tabTimersDown[id]);
		tabTimersUp[id] = setTimeout("$('#"+id+"').find('.shadow').stop(true, true).slideUp(100, function () { $(this).parent().removeClass('on');	});", 100);
	});

	// Load next steps into nav menu.
	$(document).eachUnique(function ()
	{
		$.get('/helpers/next-steps.html', function(data)
		{
			$('dl.nav-main dl.main-menu').after(data);
		});
	});

	/**
	* Lightbox form submission.
	*/
	$('div.lightbox form').bindUnique('submit', function ()
	{
		if (this.enctype == 'multipart/form-data')
		{
			return true;
		}

		var action = $(this).attr('action');
		action += (action.indexOf('?') === -1 ? '?lightbox' : '&lightbox');

		$lightboxContent = $('div.lightbox').parent();

		//$lightboxContent.scrollTo('normal', 'swing', $lightboxContent);

		$lightboxContent.css({opacity: .3}).load(action, $(this).serializeArray(), function ()
		{
			//$(window).trigger('scroll.DOMWindow');
			$.fancybox.resize();
			
			$lightboxContent.css({opacity: ''});

			$('.list').each(function ()
			{
				var requestUrl = $(this).find('.pagination .request-url').text();
				if (requestUrl)
				{
					$(this).css({opacity: .5}).addClass('loading')
						.load(requestUrl, function ()
						{
							$(this).css({opacity: 1}).removeClass('loading');
						});
				}
			});
		});
		return false;
	});
	$('div.lightbox a.close').bindUnique('click', function ()
	{
		$.fancybox.close();
		return false;
	});

	// Client testimonial links.
	$('a.testi').eachUnique(function ()
	{
		this.href = this.href.replace(/#/, '/');
		$(this).addClass('lightbox');
	});

	// Lightbox integration.
	$('a.login, a.pop, a.lightbox').eachUnique(function ()
	{
		this.href += this.href.indexOf('?') === -1 ? '?lightbox' : '&lightbox';
	});

	// Lightbox integration.
	$('a.pop, a.lightbox').eachUnique(function ()
	{
		$(this).fancybox();
	});

	// Setup login links.
	$('a.login').eachUnique(function ()
	{
		$(this).fancybox({
			'scrolling': 'no'
		});
	});

	// Marketo links.
	$('a.marketo').eachUnique(function ()
	{
		$(this).fancybox({
			'type': 'iframe'
		});
	});

	// Demo links.
	$('a.demo').eachUnique(function ()
	{
		$(this).fancybox({
			'scrolling': 'no',
			'type': 'ajax',
			'onComplete': function () {
				var demo_file = $('#demo-video span.demofile').text();
				var demo_name = $('#demo-video span.demoname').text();
				var flashvars = {};
				var params = {
					wmode: "opaque"
				};
				var attributes = {};
				attributes.id = "flashcontent";
				swfobject.embedSWF(demo_file, "flashswf", "650", "490", "9.0.0", "expressInstall.swf", flashvars, params, attributes);

				setTimeout('playFlashVideo()', 2500);

				function setCookie(c_name, value, expiredays) {
					var exdate = new Date();
					exdate.setDate(exdate.getDate() + expiredays);
					document.cookie = c_name + "=" + escape(value) +
							((expiredays == null) ? "" : ";expires=" + exdate.toGMTString());

				}

				function getCookie(c_name) {
					if (document.cookie.length > 0) {
						c_start = document.cookie.indexOf(c_name + "=");
						if (c_start != -1) {
							c_start = c_start + c_name.length + 1;
							c_end = document.cookie.indexOf(";", c_start);
							if (c_end == -1) c_end = document.cookie.length;
							return unescape(document.cookie.substring(c_start, c_end));
						}
					}
					return "";
				}

				function issetCookie(c_name) {
					value = getCookie(c_name);
					if (value != null && value != "") {
						return 1;
					}
					else {
						return 0;
					}
				}

				function deleteCookie(cookie_name) {
					var cookie_date = new Date();  // current date & time
					cookie_date.setTime(cookie_date.getTime() - 1);
					document.cookie = cookie_name += "=; expires=" + cookie_date.toGMTString();
				}

				$('#demo-video form#demo-contact').submit(function ()
				{
					return false;
				});

				$('#demo-video form#demo-contact p.cta3 a').click(function ()
				{
					// Validate form.
					var errors = 0;
					$('#demo-video form#demo-contact label.error').removeClass('error');
					$('#demo-video form#demo-contact label.required input').each(function ()
					{
						if (!$(this).val())
						{
							$(this).parents('label').addClass('error');
							errors++;
						}
					});

					// Valid?
					if (errors == 0)
					{
						setCookie("validatedForm", 1, 1);

						// Send data to Marketo
						$.ajax({
							type: "POST",
							async: true,
							url: "/assets/marketo-submit",
							data: "email="+$('#demo-video form#demo-contact .email input').val(),
							success: function(data) {
								mktoMunchkin("126-DHQ-057");
								//https://126-dhq-057.mktoresp.com/
								//alert("mktoMunchkin = "+mktoMunchkin);

								$form = $('#demo-video form#demo-contact');
								mktoMunchkinFunction("associateLead", {
									"FirstName": $form.find('.first_name input'),
									"LastName": $form.find('.last_name input'),
									"Company": $form.find('.company input'),
									"Title": $form.find('.job_title input'),
									"Email": $form.find('.email input'),
									"Country": $form.find('.country input'),
									"LeadSource": 'Web: Registration',
									"Lead Source - sub": demo_name,
									"Marketing Campaign Name": 'reg_WebDemo_2010'
								}, data);
							}
						});

						$('#demo-video form#demo-contact input').attr('disabled', true);
						alert('Thank You');
					}

					
					return false;
				});
			}
		});

		// Old style demos.
		/*$(this).fancybox({
			'type': 'iframe',
			'scrolling': 'no',
			'width': 756,
			'height': 430,
			'margin': 0,
			'padding': 0
		});*/
	});
	

	// Tabify all menus.
	$('#menu').eachUnique(function ()
	{
		$(this).tabify();
	});

	// New style tabs (better!)
	$('dl.tabs').eachUnique(function ()
	{
		if (location.hash)
		{
			$(this).find('a[href='+location.hash+']').parent().addClass('active');
		}

		$(this).find('dd').each(function()
		{
			var hash = $(this).find('a').attr('href');
			var id = hash;
			if (hash)
			{
				if ($(this).hasClass('active'))
				{
					$(id).show();
				}
				else
				{
					$(id).hide();
				}
			}
		});

		$(this).find('dd a').each(function()
		{
			$(this).attr('href', $(this).attr('href') + '-tab');

			$(this).click(function ()
			{
				var hadClass = $(this).parent().hasClass('active');

				var hash = $(this).parents('dl.tabs').find('dd.active a').attr('href');
				if (hash)
				{
					$(this).parents('dl.tabs').find('dd.active').removeClass('active');
					var id = hash.substring(0, hash.length-4);
					$(id).slideUp();
				}

				if (!hadClass)
				{
					$(this).parent().addClass('active');
					var hash = $(this).attr('href');
					var id = hash.substring(0, hash.length-4);
					$(id).slideDown();
				}
			});
		});
	});

	// Tool tips
	$("a.tip").tooltip({
	   // tweak the position
	   offset: [10, 2],
	   // use the "slide" effect
	   effect: 'slide'
	// add dynamic plugin with optional configuration for bottom edge
	}).dynamic({ bottom: { direction: 'down', bounce: true } });

	// Confirm buttons.
	$('a.confirm').bindUnique('click', function ()
	{
		if (!confirm(this.title+'?'))
		{
			return false;
		}
	});

	// Submit buttons as links.
	$('a.submit').bindUnique('click', function ()
	{
		$(this).parents('form').trigger('submit');
		return false;

	}).after('<input type="submit" class="hidden" />');

	/**
	* Pagination.
	*/
	$('div.pagination a').bindUnique('click', function (event)
	{
		$(this).parents('div.list')
			.css({opacity: .3})
			.load(this.href, function ()
			{
				$(this).css({opacity: 1});
			});

		if (!$(this).parents('div.list').find('*').first().hasClass('pagination'))
		{
			$(this).parents('div.list').scrollTo('normal', 'swing');
		}

		return false;
	});

	/**
	* Load paginating lists.
	*/
	$('.paginator').eachUnique(function ()
	{
		var href = $(this).find('a').attr('href');
		href += href.indexOf('?context') === -1 ? '?context' : '&context';
		$(this).css({opacity: .5}).addClass('paginator-loading')
			.load(href ? href : window.location.href, function ()
			{
				$(this).animate({opacity: 1}, 'fast').removeClass('paginator-loading');
			});
	});

	
});

/**
* jQuery pugins.
*/
jQuery.fn.extend(
{
	/**
	* Allows a window to scroll to an element.
	*/
	scrollTo: function (speed, easing)
	{
		return this.each(function ()
		{
			var targetOffset = $(this).offset().top - 20;
			$('html,body').animate({scrollTop: targetOffset}, speed, easing);
		});
  	},
  	
  	/**
  	* Checks and notes whether an element has behaviors already.
  	*/
  	bindUnique: function (event, callback)
  	{
  		//this.unbind(event, callback);
  		//return this[event](callback);

  		return this.each(function ()
  		{
  			var key = new String(callback).replace(/[^a]/, '');
  			this.__uniqueEvents = this.__uniqueEvents || [];
  			if (jQuery.inArray(key, this.__uniqueEvents) == -1)
  			{
  				$(this)[event](callback);
  				this.__uniqueEvents[this.__uniqueEvents.length] = key;
  			}
  		});
  	},
  	
  	/**
  	* Apply a method to elements only once
  	*/
  	eachUnique: function (callback)
  	{
  		return this.each(function ()
  		{
  			var key = new String(callback).replace(/[^a]/, '');
  			this.__uniqueCallbacks = this.__uniqueCallbacks || [];
  			if (jQuery.inArray(key, this.__uniqueCallbacks) == -1)
  			{
  				callback.call(this);
  				this.__uniqueCallbacks[this.__uniqueCallbacks.length] = key;
  			}
  		});
  	},

	/**
	* Validate a simple JS form.
	*/
	validate: function ()
	{
		var result = true;

		// Required.
		this.find('div.required input, div.required textarea, div.required select, input.required, textarea.required, select.required').each(function ()
		{
			if (!$(this).attr('disabled') && !$(this).val())
			{
				result = false;
				$(this).css({backgroundColor: '#FFAABB'}).animate({backgroundColor: 'white'});
			}
		});

		return result;
	}
});

/**
* Color animation plugin.
* Courtesy of http://plugins.jquery.com/project/color
*/
(function(jQuery){

	// We override the animation for all of these color styles
	jQuery.each(['backgroundColor', 'borderBottomColor', 'borderLeftColor', 'borderRightColor', 'borderTopColor', 'color', 'outlineColor'], function(i,attr){
		jQuery.fx.step[attr] = function(fx){
			if ( fx.state == 0 ) {
				fx.start = getColor( fx.elem, attr );
				fx.end = getRGB( fx.end );
			}

			fx.elem.style[attr] = "rgb(" + [
				Math.max(Math.min( parseInt((fx.pos * (fx.end[0] - fx.start[0])) + fx.start[0]), 255), 0),
				Math.max(Math.min( parseInt((fx.pos * (fx.end[1] - fx.start[1])) + fx.start[1]), 255), 0),
				Math.max(Math.min( parseInt((fx.pos * (fx.end[2] - fx.start[2])) + fx.start[2]), 255), 0)
			].join(",") + ")";
		}
	});

	// Color Conversion functions from highlightFade
	// By Blair Mitchelmore
	// http://jquery.offput.ca/highlightFade/

	// Parse strings looking for color tuples [255,255,255]
	function getRGB(color) {
		var result;

		// Check if we're already dealing with an array of colors
		if ( color && color.constructor == Array && color.length == 3 )
			return color;

		// Look for rgb(num,num,num)
		if (result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(color))
			return [parseInt(result[1]), parseInt(result[2]), parseInt(result[3])];

		// Look for rgb(num%,num%,num%)
		if (result = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(color))
			return [parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55];

		// Look for #a0b1c2
		if (result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color))
			return [parseInt(result[1],16), parseInt(result[2],16), parseInt(result[3],16)];

		// Look for #fff
		if (result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color))
			return [parseInt(result[1]+result[1],16), parseInt(result[2]+result[2],16), parseInt(result[3]+result[3],16)];

		// Otherwise, we're most likely dealing with a named color
		return colors[jQuery.trim(color).toLowerCase()];
	}
	
	function getColor(elem, attr) {
		var color;

		do {
			color = jQuery.curCSS(elem, attr);

			// Keep going until we find an element that has color, or we hit the body
			if ( color != '' && color != 'transparent' || jQuery.nodeName(elem, "body") )
				break; 

			attr = "backgroundColor";
		} while ( elem = elem.parentNode );

		return getRGB(color);
	};
	
	// Some named colors to work with
	// From Interface by Stefan Petre
	// http://interface.eyecon.ro/

	var colors = {
		aqua:[0,255,255],
		azure:[240,255,255],
		beige:[245,245,220],
		black:[0,0,0],
		blue:[0,0,255],
		brown:[165,42,42],
		cyan:[0,255,255],
		darkblue:[0,0,139],
		darkcyan:[0,139,139],
		darkgrey:[169,169,169],
		darkgreen:[0,100,0],
		darkkhaki:[189,183,107],
		darkmagenta:[139,0,139],
		darkolivegreen:[85,107,47],
		darkorange:[255,140,0],
		darkorchid:[153,50,204],
		darkred:[139,0,0],
		darksalmon:[233,150,122],
		darkviolet:[148,0,211],
		fuchsia:[255,0,255],
		gold:[255,215,0],
		green:[0,128,0],
		indigo:[75,0,130],
		khaki:[240,230,140],
		lightblue:[173,216,230],
		lightcyan:[224,255,255],
		lightgreen:[144,238,144],
		lightgrey:[211,211,211],
		lightpink:[255,182,193],
		lightyellow:[255,255,224],
		lime:[0,255,0],
		magenta:[255,0,255],
		maroon:[128,0,0],
		navy:[0,0,128],
		olive:[128,128,0],
		orange:[255,165,0],
		pink:[255,192,203],
		purple:[128,0,128],
		violet:[128,0,128],
		red:[255,0,0],
		silver:[192,192,192],
		white:[255,255,255],
		yellow:[255,255,0]
	};
	
})(jQuery);

// AddThis span tags to links, keep PR from leaking!
$('.addthis_loadspan span').eachUnique(function ()
{
	$(this).after('<a class="'+this.className+'"></a>');
	$(this).remove();
});
$('.addthis_loadspan').removeClass('addthis_loadspan');

// demo video playback functions
function getFlashMovieObject(movieName) {
	if (window.document[movieName]) {
		return window.document[movieName];
	}
	if (navigator.appName.indexOf("Microsoft Internet") == -1) {
		if (document.embeds && document.embeds[movieName])
			return document.embeds[movieName];
	}
	else {
		return document.getElementById(movieName);
	}
}

function playFlashVideo() {
	getFlashMovieObject("flashcontent").playFlashVideo();
}
