$(function() {
	
	var uid = false;
	var trackLocally = false;
	
	function checkOK() {
		var getObj = {
			path: window.location.pathname
		};
		$.getJSON('/download/check', getObj, function(r) {			
			uid = r.uid ? r.uid : false;;
			trackLocally = parseInt(r.trackLocally, 10) ? true : false;
		});
	}
	
	var filetypes = [];
	filetypes['pdf'] = 'PDF';
	filetypes['ppt'] = 'PowerPoint';
	filetypes['pptx'] = 'PowerPoint';
	filetypes['xls'] = 'Excel';
	filetypes['xlsx'] = 'Excel';
	filetypes['doc'] = 'Word Document';
	filetypes['docx'] = 'Word Document';
	filetypes['zip'] = 'Zip File';
	
	for (var ext in filetypes) {
		var filetype = filetypes[ext];
		$('a[href*=.'+ext+']')
			.attr('target', '_blank')
			.click(function() {
				var href = $(this).attr('href');
				// is the person logged in?
				if (uid || !trackLocally) {
					// track it
					var uri = window.location.pathname;
					var hrefa = href.split('/');
					var i = hrefa.length - 1;
					i = i >= 0 ? i : 0;
					var filepath = hrefa[i];
					var filename = uri + '/' + filepath;
					// track it on analytics
					pageTracker._trackEvent(filetype+' files', 'Download', filename);
					// and track it locally ? 
					if (trackLocally) {
						var postobj = {
							uid: uid,
							filepath: href,
							page: uri
						};
						$.post('/download/trackuserdownload', postobj, function(r) {
							// do nothing
						});
					}
					return true; // download it
				} else {
					// show the colorbox signup form
					$.fn.colorbox({
						href:'/download/register/?f='+href,
						width: 420,
						height: 660,
						onClosed: checkOK,
						opacity: 0.75
					});
					return false; // don't download it
				}
		});
	}
	
	checkOK(); //start it up
});
