/*jslint unparam: true, vars: true, white: true, nomen: true, maxerr: 50, indent: 4 */
/*global DOMAssistant, $, _gaq, addthis, document, window, location */
/*iih nordic - januar 2012 - bs - at git */

$(document).ready(function () {
	'use strict';

	// dynamic variables
	var d = {
			files: ['zip', 'exe', 'pdf', 'doc', 'xls', 'ppt', 'docx', 'ashx', 'xml'],
			pool: ['ekspreslaan.dk', 'ekspresbank.no', 'ekspresbank.dk'],
			match_pattern: false
		},
		lang = {
			mail : {
				category: 'Email',
				action: 'Click',
				label: '%1',
				value: null,
				bounce: false
			},
			download : {
				category: 'Download',
				action: '%1',
				label: '%2',
				value: null,
				bounce: false
			},
			outbound : {
				category: 'External links',
				action: 'Click',
				label: '%1',
				value: null,
				bounce: false
			},
			input : {
				category: 'Form: %1',
				action: 'Input exit: %2',
				label: 'Name: %3',
				value: null,
				bounce: false
			},
			submit : {
				category: 'Form Submit: %1',
				action: 'Value: %2',
				label: 'Name: %3',
				value: null,
				bounce: false
			}
		};

	// auxilary functions
	function concat(array, nodot) {
		var n, s;
		$(array).each(function (i, v) {
			if (i === 0) { n = ''; }
			if (i === (array.length - 1)) {
				s = '';
			} else {
				s = ',';
			}
			n = n + 'a[href*="' + (nodot ? '' : '.') + v + '"]' + s;
		});
		return n;
	}

	function construct_call(pack) {
		var p = $.extend(true, {}, lang[pack]),
			arg = $.grep(arguments, function (v) { return v !== pack; }),
			arr = ['_trackEvent'],
			man = [];						
		$.each(arg, function (i, v) {
			man.push(['%' + (i + 1), arg[i]]);
		});
		$.each(p, function (i, v) {
			if (v && !!v.match(/%\d/)) {
				var newv = v;
				$.each(man, function (ii, vv) {
					if (v.match(man[ii][0])) {
						newv = newv.replace(man[ii][0], man[ii][1]);
					}
				});
				p[i] = newv;
			}
			arr.push(p[i]);
		});		
		return arr;	
	}

	// define selectors
	var s = {
		pool: concat(d.pool, true),
		files: concat(d.files),
		pass: concat($.grep(d.pool, function (v) { 
				if (d.match_pattern) {
					return '.' + v !== location.host.replace('www.', '').match(d.match_pattern)[0];
				} else {
					return v !== location.host.replace('www.', '');
				}
			}), true) 
	};

	// build selectors
	var a = {
		mails: 'a[href^="mailto:"]',
		outbound: 'a[href^="http"]:not("' + s.pool + '")',
		inputs: ':input:not(:input[type^="image"], :input[type^="submit"])',
		submit: ':input[type^="image"], :input[type^="submit"]'
	};

	// track mails, outbound and downloads
	$(a.mails).each(function () {
		var t = $(this),
			email = t.attr('href').replace('mailto:', '');
		t.click(function (e) {
			_gaq.push(construct_call('mail', email));
		});
	});

	$(a.outbound).each(function () {
		var t = $(this),
			href = t.attr('href');
		t.click(function () {
			_gaq.push(construct_call('outbound', href));
		});	
	});

	$(s.files).each(function () {		
		var t = $(this),
			href = t.attr('href'), 
			vv,
			type;
		$(d.files).each(function (i, v) {
			vv = '.' + v;
			if (href.indexOf(vv) !== -1) { type = v; }
		});	
		t.click(function () {
			_gaq.push(construct_call('download', type, href));
		});	
	});	

	// passing visitors 
	$(s.pass).each(function () {
		var t = $(this),
			href = t.attr('href');
		_gaq.push(function () {
			var _gat,
				pt = _gat._getTrackerByName();
			t.attr('href', pt._getLinkerUrl(href));
		});
	});

	// track forms
	$(a.inputs).each(function () {
		var t = $(this),
			page = location.pathname;
		t.blur(function () {
			if (t.val().length > 0) {
				_gaq.push(construct_call('input', page, t.val(), t.attr('name')));
			}	
		});
	});

	$(a.submit).each(function () {
		var t = $(this),
			page = location.pathname;
		t.click(function () {
			_gaq.push(construct_call('submit', page, t.val(), t.attr('name')));
		});
	});

	// modules
	var modules = {
		get_url_vars: function () {
		    var vars = [], 
				hash,
				i,
				hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
		    for (i = 0; i < hashes.length; i += 1) {
		        hash = hashes[i].split('=');
		        vars.push(hash[0]);
		        vars[hash[0]] = hash[1];
		    }
		    return vars;
		},
		track_loan: function () {
			if (/generelkvittering/.test(location.pathname)) {
				// /generelkvitteringek
				// /generelkvitteringep
				// /generelkvitteringdc - Samlelån
				// /generelkvitteringoc - OneCard
				
				var url = modules.get_url_vars(),
					id = url.loan_applicantid,
					store = url.loan_market,
					amount = url.loan_amount.toString(),
					city = url.loan_city || '',
					sku = url.loan_id.toString(),
					name = url.loan_name, // clean
					type = url.loan_type,
					country = /\.dk/.test(document.domain) ? 'Denmark' : 'Norway';
					
				if (id && amount && sku) {
					_gaq.push(['_addTrans', id, store, amount, '0', '0', city, '', country]);
					_gaq.push(['_addItem', id, sku, name, type, amount, '1']);
					_gaq.push(['_trackTrans']); 
				}
			}
		}
	};
	
	// run modules
	modules.track_loan();	
});
