/**
 * jQuery Google Analytics Event Tracker wrapper Plugin
 * Gaet 1.1 - By Creuna (http://www.creuna.se)
 *
 * Gaet Copyright (c) 2011 Creuna.
 * Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php
*/

(function($) {
	$.fn.extend({
		gaTrack: function(options) {
			//configurable options
			var o = $.extend({
				trackEvent: true, //If event should be tracked 
				trackPageview: false, //If pageview should be tracked
				url: "Undefined", //Page location to be added in trackEvent and/or trackPageView
				category: "Undefined", //The name you supply for the group of objects you want to track.
			    action: "Undefined", //A string that is uniquely paired with each category, and commonly used to define the type of user interaction for the web object.
			    label: null, //An optional string to provide additional dimensions to the event data.
			    triggerClick: false, //Trigger self click after track event has been added. Use if there's already a click function defined.
				linkUrl: "Undefined", //Url of clicked link
				timeout: false, //If timeout should be applied
				trackingDelay: 200 //Delay to be added to give Google Analutics time to track properly
			}, options);

            var m = new RegExp("[\\?|&]" + "gaMode" + "=(.*?)($|&|#)").exec(document.location);	            

		    return this.each(function() {
	            var obj = $(this);
	            if(m !=null && m[1] === "test"){
	                obj.css("outline", "3px dotted blue");
	                obj.attr("title", "trackEvent: "+o.trackEvent +", trackPageview: "+ o.trackPageview +", url: "+o.url+", category: "+ o.category +", activity: "+o.action +", label: "+o.label);
                } else {
					//if event or PageView or both
					if(o.trackEvent && o.trackPageview){
						sendEventAndPageview();
					}else if(o.trackEvent){
						sendEvent();
					}else{
						//must be trackPageView
						sendPageview();
					}
                }

				function sendEventAndPageview(){
					if(o.triggerClick){
						_gaq.push(['_trackPageview', o.url],['_trackEvent',o.category, o.action, o.label]);
						if(o.timeout){
							setTimeout('document.location = "' + o.linkUrl + '"', o.trackingDelay);
							return false;
						}
                    } else {
						obj.bind('click', function() {
							 _gaq.push(['_trackPageview', o.url],['_trackEvent',o.category, o.action, o.label]);
							if(o.timeout){
								setTimeout('document.location = "' + o.linkUrl + '"', o.trackingDelay);
						  		return false;
							}
                        });
                    }
					return false;
				}

				function sendEvent(){
					if(o.triggerClick){
                        _gaq.push(['_trackEvent', o.category, o.action, o.label]);
                    } else {
                       obj.bind('click', function() {
	                        _gaq.push(['_trackEvent',o.category, o.action, o.label]);
                       });
                    }
				}

				function sendPageview(){
					if(o.triggerClick){
						_gaq.push(['_trackPageview', o.url]);
						if(o.timeout){
							setTimeout('document.location = "' + o.linkUrl + '"', o.trackingDelay);
						    return false;
                        }
					} else {
                        obj.bind('click', function() {
                        	_gaq.push(['_trackPageview', o.url]);
							if(o.timeout){
								setTimeout('document.location = "' + o.linkUrl + '"', o.trackingDelay);
						  	    return false;
						    }                        	
                        });
                    }
				}
		    	
            });
		}
	});
})(jQuery);

$.fn.setCustomVariable = function() {
	//Set custom variable depending on if user is "Privat", "Företag" or "Ombud"
	//Note: This function differs from the others as it sets "_setCustomVar", that why we push directly instead of in generic function as above
	//_gaq.push(['_setCustomVar', 1, 'Typ av besökare','[Besökartyp]',1]);
	obj = $(this);
	obj.each(function() {
		var url = this.pathname;
		switch (url.toLowerCase()) {
		case "/privat/":
			$(this).click(function() {
				_gaq.push(['_setCustomVar', 1, 'Typ av besökare', 'Privat', 1]);
			});
			break;
		case "/foretag/":
			$(this).click(function() {
                _gaq.push(['_setCustomVar', 1, 'Typ av besökare', 'Företag', 1]);
			});			
			break;
		case "/foretag/ombud/":
			$(this).click(function() {
			    _gaq.push(['_setCustomVar', 1, 'Typ av besökare', 'Ombud', 1]);
			});			
			break;
		default:
			break;
		}
	});
};

$.fn.trackExternalLink =  function(){
	//External links
	//"_gaq.push(['_trackPageview', '/virtual/external/[webbadressutanprotokoll]/']);
    obj = $(this);
	var boolTimeout = true;
    obj.each(function(){
		if(typeof($(this).attr('href')) !== 'undefined'){
            var c = this;
            if(!c.href.match(/^mailto\:/) && c.hostname != location.hostname) {            	
            	$(this).click(function() {
            	    boolTimeout = true;
            	    if (typeof($(this).attr('target')) !== 'undefined') {
            		    if ($(this).attr('target') == "_blank") {
            			    boolTimeout = false;
            		    }
            	    }
            	    $(this).gaTrack({ trackPageview: true, trackEvent: false, url: '/virtual/external/' + c.hostname + c.pathname, timeout: boolTimeout, triggerClick:true });
                });
            }
		}
    });
};

$.fn.trackFilesInContentDownload =  function(){	
    //File downloads
	//Note: push differs depending on where files are located ("Privat", "Foretag" or "Foretag/Ombud")
	var files = $(this).find("a[href$='.pdf'], a[href$='.doc'], a[href$='.docx'], a[href$='.ppt'], a[href$='.pptx'], a[href$='.pps'], a[href$='.ppsx'], a[href$='.xls'], a[href$='.xlsx'], a[href$='.exe'], a[href$='.vcf'], a[href$='.png'], a[href$='.gif'], a[href$='.jpg'], a[href$='.jpeg'], a[href$='.eps']");
	
	var gaGetFileType = function(path) {
	    return path.substr(path.lastIndexOf(".")+1,path.length);
	};

	var area = 0;
	var pathname = location.pathname.toLowerCase();
	if(pathname.indexOf("/privat/") > -1) {
		area = 1;
	} else if (pathname.indexOf("/foretag/") > -1) {
		area = 2;
	} else if (pathname.indexOf("/om-alecta/") > -1) {
		area = 3;
	}
    var boolTimeout = true;
    files.each(function(){
		var url = $(this).attr('href'),
        	filetype = gaGetFileType(url);

		switch(area) {
		    case 1:
		    	//_gaq.push(['_trackPageview', '/virtual/download/privat/[filtyp]/[sökvägtilldokumentet]'],['_trackEvent', 'sjalvbetjaningsaktivitet Privat', 'nedladdning', '[sökvägtilldokumentet]']);
		    	$(this).click(function() {
    	            boolTimeout = true;
    	            if(typeof($(this).attr('target')) !== 'undefined') {
    		            if($(this).attr('target') == '_blank') {
    			            boolTimeout = false;
    		            }
    	            } 
		    	    $(this).gaTrack({trackPageview: true, trackEvent: true, url: '/virtual/download/privat/'+filetype+'/'+url, category: 'sjalvbetjaningsaktivitet Privat', action: 'nedladdning', label: url, linkUrl : url, timeout:boolTimeout, triggerClick:true });	
		    	});
		    	break;		    	
		    case 2:
		    	//_gaq.push(['_trackPageview', '/virtual/download/foretag/[filtyp]/[sökvägtilldokumentet]'],['_trackEvent', 'sjalvbetjaningsaktivitet Foretag', 'nedladdning', '[sökvägtilldokumentet]']);
		    	$(this).click(function() {
    	            boolTimeout = true;
    	            if(typeof($(this).attr('target')) !== 'undefined') {
    		            if($(this).attr('target') == '_blank') {
    			            boolTimeout = false;
    		            }
    	            } 
		    	    $(this).gaTrack({trackPageview: true, trackEvent: true, url: '/virtual/download/foretag/'+filetype+'/'+url, category: 'sjalvbetjaningsaktivitet Foretag', action: 'nedladdning', label: url, linkUrl : url, timeout:boolTimeout, triggerClick:true });
		    	});		    	
		    	break;
		    case 3:
		    	//_gaq.push(['_trackPageview', '/virtual/download/om-alecta/[filtyp]/[sökvägtilldokumentet]);
		    	$(this).click(function() {
    	            boolTimeout = true;
    	            if(typeof($(this).attr('target')) !== 'undefined') {
    		            if($(this).attr('target') == '_blank') {
    			            boolTimeout = false;
    		            }
    	            } 
		    	    $(this).gaTrack({trackPageview: true, trackEvent: false, url: '/virtual/download/om-alecta/'+filetype+'/'+url, linkUrl : url, timeout:boolTimeout, triggerClick:true });
		    	});		    	
		    	break;
		    default :
		    	break;
		}

    });
};

$.fn.trackEmailLink = function(){
	//e-mail link clicks
	//_gaq.push(['_trackEvent', 'Skriva ut', 'Skriva ut', 'URL']);
	obj = $(this);
    obj.each(function(){
		var emailLink = $(this).attr('href'), 
        	receiver = emailLink.replace(/^mailto:/i, "");
        $(this).gaTrack({trackPageview: true, trackEvent: false, url: '/virtual/kontakt/epost/'+receiver, linkUrl : emailLink, timeout:true });        
    });
};

$.fn.trackPrintLink = function(){
	//Print link clicks
	//_gaq.push(['_trackEvent', 'Skriva ut', 'URL']);
	obj = $(this);
    obj.each(function(){
		var url = window.location.href;
		$(this).gaTrack({trackPageview: false, trackEvent: true, category: "Skriva ut", action: "Skriva ut", label: url}); 
	});
};

$.fn.trackExpand =  function(){
	//Toggled information
	//_gaq.push(['_trackPageview', document.location.pathname +'?expandera=ämne']);
    obj = $(this);
    obj.each(function(){
		var url = window.location.pathname;
    	$("a:first", this).click(function() {
    		if(!$(this).hasClass("dontPushGA")){
	            var	linkName = $(this).text();
		        linkName = linkName.replace(/ /g, "-");
    	    	$(this).gaTrack({trackPageview: true, trackEvent: false, url: url+'?expandera='+linkName, triggerClick:true });     	    	
    	    }
    	    $(this).toggleClass("dontPushGA");    		
    	});
    });
};

$.fn.trackUserAgreement = function() {
	// Search on Personnr (Privat)
	//_gaq.push(['_trackPageview', '/virtual/personnummersokning/inskickat'], ['_trackEvent', 'sjalvbetjaningsaktivitet Privat', 'personnummersokning', '[resultat]']);
	obj = $(this);
	obj.each(function() {
		var message = $("#content .userAgreement h1").text();
		$(this).gaTrack({ trackPageview: true, trackEvent: true, url: '/virtual/personnummersokning/inskickat', category: 'sjalvbetjaningsaktivitet Privat', action: 'personnummersokning', label: message, triggerClick: true });
	});
};

$.fn.trackPersonnrError = function() {
	//Error in personnummersök
	//_gaq.push(['_trackPageview', '/virtual/personnummersokning/felmeddelande']);
	obj = $(this);
	if(obj.length) {
		$(this).gaTrack({ trackPageview: true, trackEvent: false, url: '/virtual/personnummersokning/felmeddelande', triggerClick: true });
	}
};

$.fn.trackPensionCalculate = function() {
	//Calculate Pension
	//_gaq.push(['_trackPageview', '/virtual/formular/rakna-pa-din-tjanstepension/beraknat'],['_trackEvent', 'sjalvbetjaningsaktivitet Privat', 'rakna-pa-din-tjanstepension', '[typ av beräkning]']);
	obj = $(this);
    obj.each(function(){
		$(this).gaTrack({trackPageview: true, trackEvent: true, url: '/virtual/formular/rakna-pa-din-tjanstepension/beraknat', category: 'sjalvbetjaningsaktivitet Privat', action: 'rakna-pa-din-tjanstepension', label: 'Beräkna din tjänstepension', triggerClick: true});
	});
};

$.fn.trackITPKCalculate = function() {
	//Calculate ITPK
	//_gaq.push(['_trackPageview', '/virtual/formular/rakna-pa-din-tjanstepension/beraknat'],['_trackEvent', 'sjalvbetjaningsaktivitet Privat', 'rakna-pa-din-tjanstepension', '[typ av beräkning]']);
	obj = $(this);
    obj.each(function(){
		$(this).gaTrack({trackPageview: true, trackEvent: true, url: '/virtual/formular/rakna-pa-din-tjanstepension/beraknat', category: 'sjalvbetjaningsaktivitet Privat', action: 'rakna-pa-din-tjanstepension', label: 'Räkna om din ITPK', triggerClick: true});
	});	
};

$.fn.trackSearchNoHits = function() {
	//Search returns no results
	//_gaq.push(['_trackPageview', '/virtual/sok/inga-traffar'+ document.location.pathname + document.location.search]);
	obj = $(this);
    obj.each(function(){
		$(this).gaTrack({trackPageview: true, trackEvent: false, url: '/virtual/sok/inga-traffar'+ document.location.pathname + document.location.search, triggerClick: true});
	});	
};

$.fn.trackFormInteraction = function() {
	//Form interaction 
	//_gaq.push(['_trackPageview’, '/virtual/formular/interaktion/'+ document.location.pathname + document.location.search]);
	jQuery.data(document.body, 'forminteraction', 0);
	obj = $(this);
    obj.each(function(){
    	$(this).focus(function(){
    		if(!jQuery.data(document.body, 'forminteraction')) {
    			$(this).gaTrack({ trackPageview: true, trackEvent: false, url: '/virtual/formular/interaktion' + document.location.pathname + document.location.search, triggerClick:true });
    			jQuery.data(document.body, 'forminteraction', 1);
    		}
    	});
	});	
};

$.fn.trackCalculatePremiums =  function(){
	//Calculate "premiernivå" (Företag)
	//_gaq.push(['_trackPageview', '/virtual/berakna-premierniva/[länk]'], ['_trackEvent','sjalvbetjaningsaktivitet Foretag', 'berakna-premierniva', '[länk]']);
    obj = $(this);
    obj.each(function(){
    var url = $(this).attr('href'), urlMinusProtocol = url.replace(/^https?:\/\//i, "");		
	    $(this).gaTrack({trackPageview: true, trackEvent: true, url: '/virtual/berakna-premierniva/' + urlMinusProtocol, category: 'sjalvbetjaningsaktivitet Foretag', action: 'berakna-premierniva', label: url});
    });
};

$.fn.trackXFormValidatorError = function() {
	//Form errors (XForm, are loaded without postback)
	//_gaq.push(['_trackPageview', '/virtual/formular/felmeddelande'+ document.location.pathname + document.location.search]);
	obj = $(this);
	obj.each(function(){
        $(this).click(function(){
            if (typeof(ValidatorOnSubmit) == "function" && ValidatorOnSubmit() == false){
                $(this).gaTrack({ trackPageview: true, trackEvent: false, url: '/virtual/formular/felmeddelande' + document.location.pathname + document.location.search, triggerClick:true });
            	return false;
            }
        });
	});
};

$.fn.trackFormError = function() {
	//Form errors (generic, loaded on postback)
	//_gaq.push(['_trackPageview', '/virtual/formular/felmeddelande'+ document.location.pathname + document.location.search]);
	obj = $(this);
	if(obj.length) {
		$(this).gaTrack({ trackPageview: true, trackEvent: false, url: '/virtual/formular/felmeddelande' + document.location.pathname + document.location.search, triggerClick: true });
	}
};

$.fn.trackLogin = function() {
	//Log in
	if(!$("#loginLinks").length) {
		//_gaq.push(['_trackPageview', '/virtual/inloggning/privat/[URL]'], ['_trackEvent','sjalvbetjaningsaktivitet Privat', 'inloggning', '[typ av besökare]']);
		obj = $(this);
		obj.each(function() {
			var url = $(this).attr('href'), urlMinusProtocol = url.replace(/^https?:\/\//i, "");
			$(this).gaTrack({trackPageview: true, trackEvent: true, url: '/virtual/inloggning/privat/' + urlMinusProtocol, category: 'sjalvbetjaningsaktivitet Privat', action: 'inloggning', label: 'Privat'}); 	
		});
	} else {
		//_gaq.push(['_trackPageview', '/virtual/inloggning/foretag/[URL]'], ['_trackEvent','sjalvbetjaningsaktivitet Foretag', 'inloggning', '[typ av besökare]']);
		$("#loginLinks a").each(function () {
			var customertype = "Foretagskund";
			var thisText = $(this).text().toLocaleLowerCase();
			if(thisText.indexOf("ombud") > -1) {
				customertype = "Ombud";
			}
			var url = $(this).attr('href'), urlMinusProtocol = url.replace(/^https?:\/\//i, "");
			$(this).gaTrack({trackPageview: true, trackEvent: true, url: '/virtual/inloggning/foretag/' + urlMinusProtocol, category: 'sjalvbetjaningsaktivitet Foretag', action: 'inloggning', label: customertype});
		});
	}
};

$.fn.trackRss = function() {
	//RSS feeds
	//_gaq.push(['_trackPageview', '/virtual/external/webbadressminusprotokoll']);
	obj = $(this);
    obj.each(function() {
        if(typeof($(this).attr('href')) !== 'undefined'){
            var url = $(this).attr("href").toLowerCase();
            if(url.indexOf("format=rss") > -1){
        	    $(this).unbind();
        	    var urlMinusProtocol = url.replace(/^https?:\/\//i, "");
        	    $(this).gaTrack({ trackPageview: true, trackEvent: false, url: '/virtual/external/' + urlMinusProtocol });
            }
        }
    });	
};

$(document).ready(function() {
		// Tracking
		// use guerystring "gaMode=test" to see objects with events
		if(typeof(_gaq) !== 'undefined'){	
		   	$('#mainNav a').setCustomVariable();
			$('#contentAndNav a').trackExternalLink();
			$("#content .userAgreement").trackUserAgreement();
			$("#CrnSearchWrapper .error-exists").trackPersonnrError();
			
			$("#content, #sidebar").trackFilesInContentDownload();
			//Email is js-generated so must wait for script to be ready
			$(window).load(function() {
				$('a[href^="mailto:"]').trackEmailLink();
			});
			$("#printInfo a").trackPrintLink();
			$("h3.closed, h4.closed").trackExpand();
			$("#content .pension-result").trackPensionCalculate();
			$("#content .itpk-result").trackITPKCalculate();
			$("#content .ess-no-hits").trackSearchNoHits();
			$("#content :input, #sidebar :input").trackFormInteraction();
			$("#content .ftg-premierniva").trackCalculatePremiums();
			
			$("#search .log-in a").trackLogin();
			
			//xforms validator
			$("#content :input[type=submit]").trackXFormValidatorError();
			//Form errors in #content, form errors (captcha) in "Är du kund hos Alecta"
			$("ul.error:visible, #CrnSearchWrapper .error").trackFormError();			
			//RSS
			$("#rightPortlets a").trackRss();
	    }
});
