// Tracking methods: Omniture, GA(Google Analytics), Spotlight, Floodlight
// 02-11-2010
var BEXTracker = new function() {
	var pageTracker = null;
	var cachedIsDev = null;

	// / DOC READY EVENT
	$(document).ready(function() {
		try {
			if ( BEXTracker.isDev() ) {
				return;
			}
			if ( !BEXTracker.isSpanish() ) {
				BEXTracker.pageTracker = _gat._getTracker("UA-3482528-4");
			} else {
				BEXTracker.pageTracker = _gat._getTracker("UA-3482528-5");
			}
			BEXTracker.captureSource(); // capture incoming source code
			BEXTracker.pageTracker._setDomainName(".becomeanex.org");
			BEXTracker.pageTracker._setAllowHash(false);
			BEXTracker.pageTracker._trackPageview();
			BEXTracker.addLinkerEvents();			
		} catch (err) { }
	});
	
	// utility used throughout for language-specific analytics
	this.isSpanish = function() {
		if (document.BEXlanguage !== undefined && document.BEXlanguage.match(/es/i)) {
			return true;
		} else {
			return false;
		}
	}
	
	this.isDev = function() {
		if ( this.cachedIsDev !== undefined && this.cachedIsDev !== null ) {
			return this.cachedIsDev;
		}
		if ( document.location.href.match(/(staging.becomeanex|beaconfire.us)/i) ) {
			this.cachedIsDev = true; 
			return true;
		}
		this.cachedIsDev = false;
		return false;
	}

	// ///////////////////////////////////////////////////////////////////////////
	// / SYSTEM EVENTS
	// ///////////////////////////////////////////////////////////////////////////
	this.Registration_CancelRegistration = function() {
		this.statTrack('event', 'registration', 'step 1', 'cancel');
	};
	this.Registration_CancelRegistrationConfirm = function() {
		this.statTrack('event', 'registration', 'step 1', 'cancel');
	};
	this.Registration_CancelCancellingRegistration = function() {
		this.statTrack('event', 'registration', 'step 1', 'return');
	};
	this.Registration_FieldFocused = function(fieldName) {
		this.statTrack('event', 'registration', 'step 2', fieldName);
	};
	this.Registration_LearnMoreAboutTobacco = function() {
		this.statTrack('event', 'registration', 'step 2',
				'types of tobacco popup');
	};
	this.Registration_GotoPage1 = function() {
		this.statTrack('event', 'registration', 'step 2', 'back-to-1');
	};
	this.Registration_GotoPage2 = function() {
		if ( this.isSpanish() ) {
			this.invokeSpotlightTag("http://ad.doubleclick.net/activity;src=1480195;type=2009-452;cat=spani585;ord=1");
		} else {
			this.invokeSpotlightTag("http://ad.doubleclick.net/activity;src=1480195;type=2009-611;cat=bexor480;ord=1");
		}
	};
	this.Registration_Page2Submit = function() {
		this.statTrack('event', 'registration', 'step 2', 'submit');
		if (document.location.href.match(/create-profile/)) {
			this.trackOmnitureRegistration('event3');
			this.Registration_ShowSpotlightTags();
			this.statTrack('virtpage', '/reg-complete');
			if ( this.isSpanish() ) {
				this.invokeSpotlightTag("http://ad.doubleclick.net/activity;src=1480195;type=2009-452;cat=spani532;ord=1");
			} else {
				this.invokeSpotlightTag("http://ad.doubleclick.net/activity;src=1480195;type=2009-611;cat=bexor003;ord=1");
			}
		}
	};
	this.Registration_EditProfile = function() {

	}
	this.Registration_CreateProfileLandOnPage = function() {
		if ( this.isSpanish() ) {
			this.invokeSpotlightTag("http://ad.doubleclick.net/activity;src=1480195;type=2009-452;cat=spani642;ord=1");
		} else {
			this.invokeSpotlightTag("http://ad.doubleclick.net/activity;src=1480195;type=2009-611;cat=bexor412;ord=1");
		}
	};
	this.CalendarTracker_Navigator = function(direction) {
		this.statTrack('event', 'cig tracker', 'calendar nav', direction);
	};
	this.CalendarTracker_SwitchMode = function(context) {
		this.statTrack('event', 'cig tracker', 'switch mode', context);
	};
	this.CalendarTracker_EnterQuitDateMode = function() {
		this.statTrack('event', 'cig tracker', 'enter quit mode');
	};
	this.CalendarTracker_LeaveQuitDateMode = function() {
		this.statTrack('event', 'cig tracker', 'leave quit mode');
	};
	this.CalendarTracker_SaveData = function() {
		this.statTrack('event', 'cig tracker', 'save data');
	};
	this.CalendarTracker_AddEventRows = function() {
		this.statTrack('event', 'cig tracker', 'add event rows');
	};
	this.CalendarTracker_EditEventRow = function() {
		this.statTrack('event', 'cig tracker', 'edit event row');
	};
	this.CalendarTracker_SetSelectedQuitDate = function() {
		this.statTrack('event', 'quit date', 'set quit early', 'used selected');
	};
	this.CalendarTracker_SetRecommendedQuitDate = function() {
		this.statTrack('event', 'quit date', 'set quit early', 'used recommended');
	};
	this.CalendarTracker_SubmitQuitForm = function() {
		this.statTrack('event', 'quit date', 'set quit');
	};
	this.CalendarTracker_SubmitQuitFormTooEarly = function() {
		this.statTrack('event', 'quit date', 'submit quit form too early');
	};
	this.CalendarTracker_CancelQuitForm = function() {
		this.statTrack('event', 'quit date', 'cancel quit form');
	};
	this.CalendarTracker_FailQuitForm = function() {
		this.statTrack('event', 'quit date', 'invalid quit form');
	};
	this.CalendarTracker_ShowQuitForm = function() {
		this.statTrack('event', 'quit date', 'show quit form');
	};
	this.Registration_ShowSpotlightTags = function() {
		if ( this.isSpanish() ) {
			this.docWriteImage("http://ad.n2434.doubleclick.net/activity;src=1480195;type=2009g759;cat=bexes570;ord=");
			this.docWriteImage("http://ad.n2434.doubleclick.net/activity;src=1480195;type=2009g828;cat=bexes976;ord=1;num=");
			this.docWriteImage("http://ad.n2434.doubleclick.net/activity;src=1480195;type=2009g759;cat=bexes098;ord=");
			this.docWriteImage("http://ad.n2434.doubleclick.net/activity;src=1480195;type=2009g828;cat=bexes445;ord=1;num=");
			this.docWriteImage("http://ad.n2434.doubleclick.net/activity;src=1480195;type=2009g759;cat=bexes691;ord=");
			this.docWriteImage("http://ad.n2434.doubleclick.net/activity;src=1480195;type=2009g828;cat=bexes364;ord=1;num=");
		} else {
			this.docWriteImage("http://ad.n2434.doubleclick.net/activity;src=1480195;type=2009g606;cat=bexor837;ord=");
			this.docWriteImage("http://ad.n2434.doubleclick.net/activity;src=1480195;type=2009g584;cat=bexor031;ord=1;num=");
			this.docWriteImage("http://ad.n2434.doubleclick.net/activity;src=1480195;type=2009g606;cat=bexor485;ord=");
			this.docWriteImage("http://ad.n2434.doubleclick.net/activity;src=1480195;type=2009g584;cat=bexor828;ord=1;num=");
			this.docWriteImage("http://ad.n2434.doubleclick.net/activity;src=1480195;type=2009g606;cat=bexor376;ord=");
			this.docWriteImage("http://ad.n2434.doubleclick.net/activity;src=1480195;type=2009g584;cat=bexor535;ord=1;num=");
			//this.docWriteImage("http://smp.specificmedia.com/smp/v=5;m=1;t=1787;"); // 3955
			//this.docWriteImage("http://ad.amgdgt.com/ads/?t=ap&px=6331&rnd=%n"); // 3955
			//this.docWriteImage("http://ace-tag.advertising.com/action/type=129985988/bins=1/rich=0/mnum=1516/site=695501/logs=0/betr=alf_cs=2"); // 3955
			this.docWriteImage("https://smp.specificmedia.com/smp/v=5;m=1;t=1046;ts=");
			//this.docWriteImage('http://leads.specificmedia.com/track_lead/1006/OPTIONAL_INFORMATION'); // 3955
			//this.docWriteScript("http://leads.specificmedia.com/lead_third/1006/OPTIONAL_INFORMATION"); // 3955
		}
	};

	this.trackOmnitureRegistration = function(eventName) {
		if ( eventName == 'event2' ) {
			s.clearVars("pageName,channel,server,prop1,prop2,prop22,prop35,eVar35",2);
			s.pageName = s.pageName + ':submit-page-1';
			s.prop8 = $('#birthYear').val();
			s.prop9 = $('#educationLevelID').val();
			s.prop10 = $('#ethnicityID').val();
			s.prop11 = $('#zip').val();
			s.prop12 = $('#howOften').val();
			s.prop13 = $('#describeYou').val();
			s.prop14 = $('#howLearn').val() == 'other' ? $('#howLearnOther').val() : $('#howLearn').val();
			s.prop15 = $('#emailOptin').is(':checked') ? 'yes' : 'no';
			s.prop16 = $('#mobileOptin').is(':checked') ? 'yes' : 'no';
			s.prop23 = $('#personID').val();
		} else if ( eventName == 'event3' ) {
			s.clearVars("pageName,channel,server,prop1,prop2,prop22,prop35,eVar35",2);
			if ( s.pageName.match(/submit-page-1/) ) {
				s.pageName = s.pageName.replace(/submit-page-1/,'submit-page-2');
			} else {
				s.pageName = s.pageName + ':submit-page-2';
			}
			s.prop17 = $('#howSoonSmoke').val();
			s.prop18 = $('#typeOfTobacco').val() ? $('#typeOfTobacco').val().join(':') : '';
			s.prop19 = $('#timesStopped').val();
			s.prop20 = $('#seriouslyThinking').val();
			s.prop23 = $('#personID').val();			
		}
		s.events = eventName;
		s.t();
	}
	
	this.onCreateProfile = function() {	
		var smokerType = $('#howOften').val();
		if (smokerType == 'nonsmoker') {
			this.trackOmnitureRegistration('event3');
			this.statTrack('virtpage', '/reg-complete');
			this.Registration_ShowSpotlightTags();
		} else {
			this.trackOmnitureRegistration('event2');
			this.statTrack('virtpage', '/go-to-step2');
		}
		// 3903
		if ( this.isSpanish() ) {
			this.invokeSpotlightTag("http://ad.doubleclick.net/activity;src=1480195;type=2009-452;cat=spani953;ord=1");
		} else {
			this.docWriteImage("http://smp.specificmedia.com/smp/v=5;m=1;t=1787;"); // 3955
			this.docWriteImage('http://leads.specificmedia.com/track_lead/1006/OPTIONAL_INFORMATION'); // 3955
			this.docWriteScript("http://leads.specificmedia.com/lead_third/1006/OPTIONAL_INFORMATION"); // 3955
			this.docWriteImage("http://ad.amgdgt.com/ads/?t=ap&px=6331&rnd=%n"); // 3955
			this.docWriteImage("http://ace-tag.advertising.com/action/type=129985988/bins=1/rich=0/mnum=1516/site=695501/logs=0/betr=alf_cs=2"); // 3955
			
			this.docWriteImage("http://ad.yieldmanager.com/pixel?id=609379&t=2"); // 3955/11.16
			this.docWriteImage("https://ds.contextweb.com/CDSLogger/TrackAction.aspx?AdvertiserId=2018"); // 3955/11.16
			this.docWriteScript("http://im-px.33across.com/pixel?pixelID=4977&partnerID=38&clientID=1639&key=conv&returnType=js"); // 3955/11.16
			this.docWriteScript("http://conversion.kontera.com/redirectEngine/RedirectEngine?at=3&34286be5b65d006c5256354a093cc759c6b3900acc307d3b83ffa98d496d7ea2"); // 3955/11.16
			this.docWriteScript("http://conversion.kontera.com/redirectEngine/RedirectEngine?at=3&c9e7d9048b709648b4467cd67556e25dc6b3900acc307d3b83ffa98d496d7ea2"); // 3955/11.16
			this.docWriteScript("http://conversion.kontera.com/redirectEngine/RedirectEngine?at=3&8372f1010d98c965cf6fee2e77d5cdbd8907499eaf25d28d544afa86f4cc77d0"); // 3955/11.16
			this.docWriteScript("http://conversion.kontera.com/redirectEngine/RedirectEngine?at=3&b134f046d56f0f8e950efedc6e43423fc6b3900acc307d3b83ffa98d496d7ea2"); // 3955/11.16
			
			this.invokeSpotlightTag("http://ad.doubleclick.net/activity;src=1480195;type=2009-611;cat=bexor835;ord=1");
		}
	};
	
	this.trackPromo = function( panel, promoName ) {
		if ( BEXTracker.isDev() ) {
			return;
		}
		this.pageTracker._trackEvent( 'Promos', panel, promoName );
	}

	// ///////////////////////////////////////////////////////////////////////////
	// / HELPER METHODS
	// ///////////////////////////////////////////////////////////////////////////
	// Marissa's method to track virtual pages (GA)
	this.statTrack = function(type, category, label, value) {
		if ( BEXTracker.isDev() ) {
			return;
		}		
		try {
			switch (type) {
			case "event":
				this.pageTracker._trackEvent(category, label, value);
				break;
			case "virtpage":
				this.pageTracker._trackPageview(category);
				break;
			}
		} catch (err) {}
	};

	this.trackEvent = function(page) {
		if ( BEXTracker.isDev() ) {
			return;
		}		
		try {
			this.pageTracker._trackPageview(page);
		} catch (err) {}
	};

	// href param is without the num part!
	// href should end on "ord=1"
	this.invokeSpotlightTag = function(href) {
		if ( BEXTracker.isDev() ) {
			return;
		}		
		var axel = Math.random() + "";
		var num = axel * 1000000000000000000;
		this.docWriteImage(href+";num="+num);
	};
	
	this.docWriteScript = function(href) {
		if ( BEXTracker.isDev() ) {
			return;
		}		
		$(document.body).append("<scr" + "ipt src='" + href + "'></scri" + "pt>");
	};

	this.docWriteImage = function(href) {
		if ( BEXTracker.isDev() ) {
			return;
		}		
		var tag_url = new Image();
		tag_url.src = href;
	};

	// Only links written to the page (already in the DOM) will be tagged
	// This version is for ga.js (last updated Jan 15th 2009)
	this.addLinkerEvents = function() {
		/***********************************************************************
		 * Author: Brian J Clifton Url:
		 * http://www.advanced-web-metrics.com/scripts This script is free to
		 * use as long as this info is left in
		 * 
		 * Combined script for tracking external links, file downloads and
		 * mailto links
		 * 
		 * All scripts presented have been tested and validated by the author
		 * and are believed to be correct as of the date of publication or
		 * posting. The Google Analytics software on which they depend is
		 * subject to change, however; and therefore no warranty is expressed or
		 * implied that they will work as described in the future. Always check
		 * the most current Google Analytics documentation.
		 * 
		 * Thanks to Nick Mikailovski (Google) for intitial discussions & Holger
		 * Tempel from webalytics.de for pointing out the original flaw of doing
		 * this in IE.
		 * 
		 * Modified by Beaconfire Consulting 10/14/2009 to add pagelinkers and
		 * other customizations
		 **********************************************************************/
		var as = document.getElementsByTagName("a");
		var extTrack = [ "becomeanex.org" ];
		var extDoc = [ ".pdf", ".doc", ".docx", ".xls", ".xlsx", ".zip" ];
		
		/*
		 * If you edit no further below this line, Top Content will report as
		 * follows: /ext/url-of-external-site /downloads/filename
		 * /mailto/email-address-clicked
		 */

		for ( var i = 0; i < as.length; i++) {
			var flag = 0;
			var tmp = as[i].getAttribute("onclick");

			// IE6-IE7 fix (null values error) with thanks to Julien Bissonnette
			// for this
			if (tmp != null) {
				tmp = String(tmp);
				if (tmp.indexOf('urchinTracker') > -1
						|| tmp.indexOf('_trackPageview') > -1)
					continue;
			} else {
				// Tracking outbound links off site
				for ( var j = 0; j < extTrack.length; j++) {
					if (as[i].href.indexOf(extTrack[j]) == -1
					 && as[i].href.indexOf('google-analytics.com') == -1) {
						flag++;
					} else if (document.location.href.indexOf(extTrack[j]) == -1) {
						// off-site link, but track as an internal link
						as[i].setAttribute("onclick",
								"BEXTracker.pageTracker._link(this.href);"
										+ ((tmp != null) ? tmp + ";" : "")
										+ "return false;");
					}
				}
				if (flag == extTrack.length
					&& as[i].href.indexOf("mailto:") == -1) {
					as[i].setAttribute("onclick",
						"BEXTracker.pageTracker._trackPageview('/external/' + this.href );"
						+ ((tmp != null) ? tmp + ";" : ""));
				}
				// Tracking electronic documents - doc, xls, pdf, exe, zip
				for ( var j = 0; j < extDoc.length; j++) {
					if (as[i].href.indexOf(extDoc[j]) != -1) {
						as[i].setAttribute("onclick",
								"BEXTracker.pageTracker._trackPageview('/docs/' + this.href );"
										+ ((tmp != null) ? tmp + ";" : ""));
						break;
					}
				}
				// added to track mailto links 23-Oct-2007
				// updated 31-Oct-2008 to remove break command - thanks to
				// Victor Geerdink for spotting this
				if (as[i].href.indexOf("mailto:") != -1) {
					as[i]
							.setAttribute(
									"onclick",
									"var splitResult = this.href.split(':');BEXTracker.pageTracker._trackPageview('/mailto/' + splitResult[1] );"
											+ ((tmp != null) ? tmp + ";" : ""));
				}
			}
		}
	};

	this.captureSource = function() {
		var sc = BEXTracker.getURLParam('sourcecode');
		if (sc != '') {
			var dateObj = new Date();
			dateObj.setTime(dateObj.getTime() + (30 * 24 * 60 * 60 * 1000)); // 30 days
			var options = {
				path : '/',
				expires : dateObj,
				domain : document.domain.substring(document.domain.indexOf('.') + 1)
			};
			$.cookie("sourcecode", sc, options);
		}
	};

	this.getURLParam = function(name) {
		name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
		var regexS = "[\\?&]" + name + "=([^&#]*)";
		var regex = new RegExp(regexS);
		var results = regex.exec(window.location.href);
		if (results == null) {
			return "";
		} else {
			return results[1];
		}
	};
};

// Event tracker for old flash pieces
function trackEvent(page) {
	if ( BEXTracker.isDev() ) {
		return;
	}	
	//BEXTracker.pageTracker._trackEvent(page);
	BEXTracker.pageTracker._trackEvent('homepage',page);
	//BEXTracker.pageTracker._trackPageview(page);
}
