/* 
 * Javascript to monitor external links with Google Analytics
 *
 * Copyright (C) 2005  Luca Zappa, www.lucazappa.com, luca@lucazappa.com
 *
 * Date        : 2005/11/19 (yyyy/mm/dd)
 * Last update : $Date: 2005-10-06 21:20:05 +0200 (gio, 06 ott 2005) $
 * Revision    : $Revision: 293 $
 *
 * License:
 * 
 * This program is free software; you can redistribute it and/or modify it under the terms 
 * of the GNU General Public License as published by the Free Software Foundation; either 
 * version 2 of the License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; 
 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 
 * See the GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License along with this program; 
 * if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 */
 
GA_DEBUG_FLAG=false;
function debugMsg(aMsg) {	if (GA_DEBUG_FLAG) alert(aMsg); }

function googleExtTracker() {
	debugMsg('/outgoing/'+this.href);
	urchinTracker('/outgoing/'+this.href);
}
function googleMediaTracker() {
	debugMsg('/media/'+this.href);
	urchinTracker('/media/'+this.href);
}
function detectLinks() {
	if (typeof urchinTracker != 'function') {
		debugMsg('[ERROR] urchinTracker function not found, check your google analytics installation!');
		return;
	}
	
	debugMsg('[INFO] urchinTracker correctly found.');
	//links list in the current document
	var theLinks = document.getElementsByTagName("a");
	debugMsg('[INFO] hostname='+document.location.hostname);
	//regular expression to retrieve internal link
	regExInt = new RegExp("^http.*(" + document.location.hostname + ").*$");
	//regular expression to retrieve media link (pdf, image ...)
	regExMedia = new RegExp("^.*(\.pdf|\.gif|\.jpeg|\.jpg|\.doc|\.xls|\.xml|\.phps|\.txt|\.zip|\.gz|\.js)$");
	for (i = 0; i < theLinks.length; i++) {
		debugMsg(i+') href='+theLinks[i].href);
		if (theLinks[i].href.substring(0,4)=='http') {
			//is an onclick event already defined?
			if (theLinks[i].onclick==undefined || theLinks[i].onclick==null) {
				//is an internal link?
				if (regExInt.test(theLinks[i].href)) {
					if (regExMedia.test(theLinks[i].href)) {
						debugMsg("[INFO] internal link to media ["+theLinks[i].href+"]");
						theLinks[i].onclick=googleMediaTracker;
					}
				}
				else {
					debugMsg("[INFO] external link ["+theLinks[i].href+"]");
					theLinks[i].onclick=googleExtTracker;
				}
			}
		}
	}
}
