var DGA = {
	PREMISE_ID_VARIABLE : "prid",
	PREMISE_NAME_CSS : "#main-large h1.premises",
	PREMISE_CATEGORY_CSS : "#main-large h3.gray",
	PREMISE_NAME_CSS_SIFR : "#main-large h1 span",
	PREMISE_CATEGORY_CSS_SIFR : "#main-large h3 span",
	SEARCH_RESULT_CSS : "div.PremisesSearchResultWrapper",
	SEARCH_FORM_BUTTON : "div.premisessearchbutton a#submitbutton span",
	CONTACT_FORM_BUTTON : "#contactbuttons a span",
	CONTACT_PHONE_DIV : "div.premisescontact-info",
	FUNNEL_PREFIX : "/dga-lokaler/",
	PAGE_PATH_SEARCH : /\/sv\/Produkter-och-tjanster\/kommersiellalokaler\/Sok-lokaler\/$/,   // regexp that should match the search URL
	PAGE_PATH_PREMISE : /\/sv\/Produkter-och-tjanster\/kommersiellalokaler\/Sok-lokaler\/Visa-lokal\/.*$/,   // regexp that should match the premise URL
	PAGE_PATH_CONTACT : /\/templates\/ContactForm.aspx\?pageid=3373.*$/,   // regexp that should match the contact URL
//	PAGE_PATH_SEARCH : /\/skanska-analytics\/search\.php.*$/,   // regexp that should match the search URL
//	PAGE_PATH_PREMISE : /\/skanska-analytics\/premise\.php\?prid=.*$/,   // regexp that should match the premise URL
//	PAGE_PATH_CONTACT : /\/skanska-analytics\/contact\.php.*$/,   // regexp that should match the contact URL
	COOKIE_PREMISE_ID : "dga0",
	COOKIE_PREMISE_NAME : "dga1",
	COOKIE_PREMISE_CATEGORY : "dga2",
	phoneNumbers : null,
	
	pageDispatcher : function () {
		try {
			if (DGA.isOnPage(DGA.PAGE_PATH_SEARCH)) {
				DGA.searchPageHandler();
			}
			else 
				if (DGA.isOnPage(DGA.PAGE_PATH_PREMISE)) {
					DGA.premisePageHandler();
				}
				else 
					if (DGA.isOnPage(DGA.PAGE_PATH_CONTACT)) {
						DGA.contactPageHandler();
					}
		} catch(e) {
		}
	},
	searchPageHandler : function () {
		DGA.trackFunnelStep("searchform");

		$(DGA.SEARCH_FORM_BUTTON).click(function () {
			DGA.trackFunnelStep("searchresult");
			return true;
		});
	},
	premisePageHandler : function () {
		DGA.trackFunnelStep("premise/" + DGA.escape(DGA.getPremiseCategory()) + "/" + DGA.escape(DGA.getPremiseName()));
		DGACookie.write(DGA.COOKIE_PREMISE_ID, DGA.getPremiseId());
		DGACookie.write(DGA.COOKIE_PREMISE_NAME, DGA.getPremiseName());
		DGACookie.write(DGA.COOKIE_PREMISE_CATEGORY, DGA.getPremiseCategory());
		DGA.phoneNumbers = {};
		
		$(DGA.CONTACT_PHONE_DIV).each(function (i) {
			if ($(this).find("i").length == 0) {  // unless contains <i>, do
				DGA.phoneNumbers[i] = DGA.getHTMLContent(this);
				$(this).attr("id", 'dga-hidden-number-' + i);
				$(this).html('<a href="#" onclick="DGA.showNumber('+i+');return false;">Visa telefonnumret &raquo;</a>');
			}
		});
	},
	showNumber : function (i) {
		$("#dga-hidden-number-" + i).html('<div class="premisescontact-info">'+DGA.phoneNumbers[i]+'</div>');
		var premiseId = DGA.getPremiseId();
		var premiseName = DGA.getPremiseName();
		var premiseCategory = DGA.getPremiseCategory();

		DGA.trackFunnelStep("phonenumber/" + DGA.escape(premiseCategory) + "/" + DGA.escape(premiseName));
		DGA.trackPremiseTransaction(premiseId, premiseName, premiseCategory);
	},
	contactPageHandler : function () {
		var premiseId = DGACookie.read(DGA.COOKIE_PREMISE_ID);
		var premiseName = DGACookie.read(DGA.COOKIE_PREMISE_NAME);
		var premiseCategory = DGACookie.read(DGA.COOKIE_PREMISE_CATEGORY);
		if ($(DGA.CONTACT_FORM_BUTTON).length > 0) { // we are on the form page if the button is there!
			DGA.trackFunnelStep("emailform/" + premiseCategory + "/" + premiseName);
		} else {  // if not, we're on the thank you page
			DGA.trackFunnelStep("emailreceipt/" + premiseCategory + "/" + premiseName);
			DGA.trackPremiseTransaction(premiseId, premiseName, premiseCategory);
			DGACookie.remove(DGA.COOKIE_PREMISE_ID);
			DGACookie.remove(DGA.COOKIE_PREMISE_NAME);
			DGACookie.remove(DGA.COOKIE_PREMISE_CATEGORY);
		}
	},
	isOnPage : function (regexp) {
		var path = window.location.pathname + document.location.search;
		return path.match(regexp);
	},
	getPremiseName : function () {
		return DGA.getHTMLContent(DGA.PREMISE_NAME_CSS_SIFR, DGA.PREMISE_NAME_CSS);
	},
	getPremiseCategory : function () {
		return DGA.getHTMLContent(DGA.PREMISE_CATEGORY_CSS_SIFR, DGA.PREMISE_CATEGORY_CSS);
	},
	getPremiseId : function () {
		var id = DGA.getQueryVariable(DGA.PREMISE_ID_VARIABLE);
		return id;
	},
	getHTMLContent : function (css, css_lowerprio) {
		var el = $(css);
		if (el) {
			return el.html();
		} else {
			if (css_lowerprio) {
				el = $(css_lowerprio);
				if (el) {
					return el.html();
				}
			}
		}
		return null;
	},
	getQueryVariable : function (variable) {
		var query = window.location.search.substring(1);
		var vars = query.split("&");
		for (var i = 0; i < vars.length; i++) {
			var pair = vars[i].split("=");
			if (pair[0] == variable) {
				return pair[1];
			}
		} 
		return null;
	},
	trackFunnelStep : function (name) {
		var path = DGA.FUNNEL_PREFIX + name;
		DGA.debug("pageView: " + path);
		pageTracker._trackPageview(path);
	},
	trackPremiseTransaction : function (id, name, category) {
		DGA.debug("transaction: " + id + ", " + name + ", " + category);
		var orderId = Math.ceil(Math.random() * 999999999);
		pageTracker._addTrans(
			orderId, // order ID - required
			"Skanska.se Lokaler", // affiliation or store name
			"1", // total - required
			"", // tax
			"", // shipping
			"", // city
			"", // state or province
			"" // country
		);
		pageTracker._addItem(
			orderId, // order ID - necessary to associate item with transaction
			id, // SKU/code - required
			name, // product name
			category, // category or variation
			"1", // unit price - required
			"1" // quantity - required
		);
		pageTracker._trackTrans();
	},
	debug : function(msg) {
		try {
//			console.debug(msg);
		} catch (e) {}
	},
	escape : function (str) {
		return escape(str).replace("/", "%2F");
	},
	init : function () {
		if (!DGA.bind(false)) {
			// add jquery as a script element in <head>
			var head = document.getElementsByTagName("head")[0];
			var script = document.createElement("script");
			script.type = "text/javascript";
			script.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js';
			head.appendChild(script);
			setTimeout(function () {DGA.bind(true);}, 10);
		}
	},
	bind : function (retry) {
		try {
			$(document).ready(function(){
				DGA.pageDispatcher();
			});
			return true;
		} catch (e) {
			if (retry) {
				setTimeout(function () {DGA.bind(true);}, 10);
			}
			return false;
		}
	},
	hasRun : false
};
var DGACookie = {
	remove : function (name) {
		DGACookie.write(name, "");
	},
	write : function(name, value) {
		var today = new Date();
		today.setTime( today.getTime() );
		var expires = 1;
		if ( expires ) {
			expires = expires * 1000 * 60 * 60 * 24;
		}
		var expires_date = new Date( today.getTime() + (expires) );
		var str = name+"="+escape( value ) + ";expires="+expires_date.toGMTString() + ";path=/;";
		document.cookie = str;
	}, 
	read : function ( name ) {
		var start = document.cookie.indexOf( name + "=" );
		var len = start + name.length + 1;
		if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
			return null;
		}
		if ( start == -1 ) return null;
		var end = document.cookie.indexOf( ";", len );
		if ( end == -1 ) end = document.cookie.length;
		return unescape( document.cookie.substring( len, end ) );
	}
};

DGA.init();

