var plstart = new Date(); //Start latency tracking timer. 
// <!--GENERIC ASYNC CODE-->
//Calls GA async script. ua variable must be set. 
var _gaq = _gaq || [];
var ua = 'UA-4339126-1'; //THIS MUST BE SET
_gaq.push(['_setAccount', ua]);
  _gaq.push(['_setDomainName', '.bluestatedigital.com']);
_gaq.push(['_trackPageview']);
(function() {
	var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();
// <!--GENERIC ASYNC CODE-->

//START LATENCY TRACKING, on completion of page load. 
//Includes jQuery if its not currently included. 

//sets global variables for this page's urls and the previous page's url. 
var prev_url = document.referrer;
var url = location.href;


//Event Bindings for 'standard' form submissions
jQuery(document).ready(function() {
 


//this is a onclick override from http://stackoverflow.com/questions/142000/; right now, only for invitationpage
//Test if this is breaking the spud()
if (typeof invitationpage != 'undefined')
{
    var oldSubmit = invitationpage.submit;
    invitationpage.submit = function() {
        jQuery(invitationpage).trigger("submit");
        oldSubmit.call(invitationpage, arguments);
    }
}
if (typeof contribution != 'undefined')
{
    var oldSubmit = contribution.submit;
    contribution.submit = function() {
        jQuery(contribution).trigger("submit");
        oldSubmit.call(contribution, arguments);
    }
}



	jQuery("form#invitationpage").submit(function() {
	jQuery.cookie("invitation", "submitted", {domain: 'bluestatedigital.com', path: '/' });
	jQuery.cookie("invitetrigger", "exists", {domain: 'bluestatedigital.com', path: '/' });

		});

	jQuery("form#signup").submit(function() {
	jQuery.cookie("signup", "submitted", {domain: 'bluestatedigital.com', path: '/' });
	jQuery.cookie("test", "exists");
		});
	
	jQuery("form#quicksignup").submit(function() {
	jQuery.cookie("signup", "submitted", {domain: 'bluestatedigital.com', path: '/' });
	jQuery.cookie("test", "exists");
		});

	jQuery("form#contribution").submit(function() {
		jQuery.cookie("contribution", "submitted", {domain: 'bluestatedigital.com', path: '/' })
		});
    });

	if(jQuery('span.signuperror').length==1) 
	{
		jQuery.cookie("signup", null, {domain: 'bluestatedigital.com', path: '/' });
 	}
	if(jQuery('div.contriberrorbanner').length )
	{
		jQuery.cookie("contribution", null, {domain: 'bluestatedigital.com', path: '/' });
	}


//sets the same variables as above, but with the query string stripped. 
var is_signup, is_donation, is_invitation, is_event, is_speakout;

var src = prev_url.split('/'); 
var prev_pagetype = src[4]; //this should work on all url structures, though assumes presence of http://. Do this better.
 
if( jQuery.cookie("signup") == "submitted" &&  (prev_pagetype=="s" || url.indexOf('?action_code=') != -1 ) )
{
	is_signup = true;
}
else if(prev_pagetype == "contribute" && jQuery.cookie("contribution") == "submitted")
{
	is_donation= true;
 
}
else if(prev_pagetype == "invite" && jQuery.cookie("invitation") == "submitted")
{
	var is_invitation = true;
 }
else if(prev_pagetype == "event")
{
	is_event = true;
}
else if(prev_pagetype == "speakout")
{
	var is_speakout = true;
}

//Creates _get array for query string
  function getUrlVars() {
	var map = {};
	var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
		map[key] = value;
	});
	return map;
}

//Create _get variable, pulling the query string
var _get = getUrlVars();

//Track the Source code as a custom variable. To Do: Configure for multiple sources
if(typeof _get["source"] != "undefined")
{
	_gaq.push(['_setCustomVar', 1, 'Source', _get["source"], 2]);
}


if(is_signup)
{
	_gaq.push(['_trackEvent', 'Conversion', 'Signup', prev_url]);
	_gaq.push(['_trackPageview', '/track/signup/'+prev_url]);
	jQuery.cookie("signup", null, {domain: '.bluestatedigital.com', path: '/' }); //semidestroy cookie so that it doesn't track twice.
	_gaq.push(['_setCustomVar', 2, 'Visitor Type', "Signup", 2]);
 }

else if(is_invitation)
{
	_gaq.push(['_trackEvent', 'Conversion', 'Invitation', prev_url]);
	_gaq.push(['_trackPageview', '/track/invitation/'+prev_url]);

jQuery.cookie("invitation", null, {domain: '.bluestatedigital.com', path: '/' }); 
}
	//Donation event, ecommerce, and pageview
else if(is_donation)
{
	jQuery.cookie("contribution", null); //destroy cookie so that it doesn't track twice.
	_gaq.push(['_trackPageview', '/track/donation/'+prev_url]); 
	_gaq.push(['_setCustomVar', 1, 'Visitor Type', "Donor", 2]);
	
	//This will only execute if the replacement variables have been written to JS as instrcuted in the header.
	if( typeof donate_val != "undefined" && typeof form_name != "undefined")
	{
	//track event with donation value
	_gaq.push(['_trackEvent', 'Conversion', 'Donation', prev_url, donate_val]);

		//Track Donation as eCommerce 
		var unixTimeMs = ((new Date()).valueOf());
		var unixTime = parseInt(unixTimeMs / 1000,10);
		var orderID = unixTime.toString();

		_gaq.push(['_addTrans',
		orderID,           // order ID - required
		'',  // affiliation or store name
		donate_val,          // total - required
		'',           // tax
		'',              // shipping
		'',       // city
		'',     // state or province
		''             // country
		]);
		_gaq.push(['_addItem',
		orderID,           // order ID - required
		form_name,           // SKU/code
		'Donation',        // product name
		'Donation',   // category or variation
		donate_val,          // unit price - required
		'1'               // quantity - required
		]);
		_gaq.push(['_trackTrans']);
		//End Track Donation as eCommerce
	}
	else
	{
		_gaq.push(['_trackEvent', 'Conversion', 'Donation', prev_url]);

	}
}
var prev_onload2 = window.onload;
window.onload=function() 
{


	var plend = new Date();
	var plload = plend.getTime() - plstart.getTime();
	// determine the thresholds
	if(plload<2000)
	{
		lc = "Very Fast";
	}
	else if (plload<5000)
	{
		lc = "Fast";
	}
	else if (plload<10000)
	{
		lc = "Medium";
	}
	else if (plload<30000)
	{
		lc = "Sluggish";
	}
	else if (plload<45000)
	{
		lc = "Slow";
	}
	else
	{
		lc="Very Slow";
	}
	var fn = document.location.pathname;
	if( document.location.search)
	{
		fn += document.location.search;
	}
	try
	{
		_gaq.push(['_trackEvent', 'Page Load',lc + ' Loading Pages', fn, Math.round(plload/1000)]);
	}
	catch(err)
	{
	}
	if(prev_onload2) prev_onload2();
};
//END LATENCY TRACKING
