	var geo_link = '';
	var story_around_me = '';
	var actualRadius = 0;
	var actualRadiusKM = 0;
	var display_radius = 0;
	var limitRadius = 0;
	var paper_name_geo = "";
	var paper_name_full = "";
	var first_time_check = true;
	var moveFlag = true;
	var flagit = false;
	var radiusflag = false;

	if(geoloc_postproxy_domain.indexOf("calgaryherald") > -1) {
		paper_name_geo = "Herald";
		paper_name_full = "Calgary Herald";
	}
	else if(geoloc_postproxy_domain.indexOf("edmontonjournal") > -1) {
		paper_name_geo = "Journal";
		paper_name_full = "Edmonton Journal";
	}
	else if(geoloc_postproxy_domain.indexOf("montrealgazette") > -1) {
		paper_name_geo = "Gazette";
		paper_name_full = "Montreal Gazette";
	}
	else if(geoloc_postproxy_domain.indexOf("ottawacitizen") > -1) {
		paper_name_geo = "Citizen";
		paper_name_full = "Ottawa Citizen";
	}
	else if(geoloc_postproxy_domain.indexOf("leaderpost") > -1) {
		paper_name_geo = "Post";
		paper_name_full = "Leader Post";
	}
	else if(geoloc_postproxy_domain.indexOf("starphoenix") > -1) {
		paper_name_geo = "Phoenix";
		paper_name_full = "Star Phoenix";
	}
	else if(geoloc_postproxy_domain.indexOf("theprovince") > -1) {
		paper_name_geo = "Province";
		paper_name_full = "The Province";
	}
	else if(geoloc_postproxy_domain.indexOf("vancouversun") > -1) {
		paper_name_geo = "Sun";
		paper_name_full = "Vancouver Sun";
	}
	else if(geoloc_postproxy_domain.indexOf("timescolonist") > -1) {
		paper_name_geo = "Colonist";
		paper_name_full = "Times Colonist";
	}
	else if(geoloc_postproxy_domain.indexOf("windsorstar") > -1) {
		paper_name_geo = "Star";
		paper_name_full = "Windsor Star";
	}

	jQuery(document).ready (
		function() { 
			jQuery('link[rel="canonical"]').each (
				function(idx, item) {
					//Try to get canonical url (only one link per page)
					geo_link = item.href;
				}
			);
			if (geo_link.length <= 0)  {
				//Canonical url not exists - get current url
				geo_link = location.href;
			}
			var geogood = navigator.geolocation+"";
			if (geogood != "undefined") {
				if((navigator.userAgent.toLowerCase()).indexOf("safari") < 0 && readCookie("allowgeo") != "yes") jQuery("#geo_stories_around").css("display","block");
				if((navigator.userAgent.toLowerCase()).indexOf("safari") > -1 && (navigator.userAgent.toLowerCase()).indexOf("chrome") > -1) jQuery("#geo_stories_around").css("display","block");
			}
			if(readCookie("allowgeo") == "yes") {
				jQuery("#geo_stories_around").css("display","none");
				show_geo_stories();
			}
		}
	); 

	function createCookie(name,value,days) {
		if (days) {
			var date = new Date();
			date.setTime(date.getTime()+(days*24*60*60*1000));
			var expires = "; expires="+date.toGMTString();
		}
		else var expires = "";
		document.cookie = name+"="+value+expires+"; path=/";
	}
	
	function readCookie(name) {
		var nameEQ = name + "=";
		var ca = document.cookie.split(';');
		for(var i=0;i < ca.length;i++) {
			var c = ca[i];
			while (c.charAt(0)==' ') c = c.substring(1,c.length);
			if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
		}
		return null;
	}
	
	function eraseCookie(name) { createCookie(name,"",-1); }

	var geoSettings = {
		r:1000,
		limit:0,
		lng:0,
		ltd:0
	} 

	function show_geo_stories()	{
		if(readCookie("allowgeo") == "yes") {
			geoSettings.ltd = readCookie("geolat");
			geoSettings.lng = readCookie("geolong");
			articles_around(geoSettings.ltd, geoSettings.lng);
			register_hit_query(geo_link, 'story', 'view', geoSettings.ltd, geoSettings.lng, null);
		}
		else {
			navigator.geolocation.getCurrentPosition (
				function(position) {
					//Get latitude 
					geoSettings.ltd = position.coords.latitude;
					geoSettings.lng = position.coords.longitude;
					flagit = true;
					createCookie("allowgeo","yes");
					createCookie("geolong",geoSettings.lng);
					createCookie("geolat",geoSettings.ltd);
					//Display aricles red around callers location 
					articles_around(geoSettings.ltd, geoSettings.lng);
					//Register hit
					register_hit_query(geo_link, 'story', 'view', geoSettings.ltd, geoSettings.lng, null);
				},
				function() { createCookie("allowgeo","no"); }
			);
		}
	}
	
	//Get top articles red around caller's location
	function top_assets_query(assetType, hitType, timeFrame, domain, latitude1, longitude1, latitude2, longitude2, max, callback) {
		assetType = encodeURIComponent(assetType);
		hitType = encodeURIComponent(hitType);
		timeFrame = encodeURIComponent(timeFrame);
		domain = encodeURIComponent(domain);
		latitude1 = encodeURIComponent(latitude1);
		latitude2 = encodeURIComponent(latitude2);
		longitude1 = encodeURIComponent(longitude1);
		longitude2 = encodeURIComponent(longitude2);
		url = 'http://' + geoloc_service_domain + '/Geometrix/Query.svc/topassets?hitType=' + hitType 
			+ '&timeFrame=' + timeFrame
			+ '&domain=' + domain 
			+ '&assetType=' + assetType 
			+ '&latitude1=' + latitude1 
			+ '&longitude1='+ longitude1
			+ '&latitude2=' + latitude2
			+ '&longitude2=' + longitude2
			+ '&max=' + max
			+ '&min=' + max
			+ '&format=JSON&callback=' + callback;
		var script = document.createElement('script');
		script.src = url;
		document.body.appendChild(script);
	}
	
	//Register hit
	function register_hit_query(url, assetType, hitType, latitude, longitude, callback) {
		var destinationUrl = 'http://' + geoloc_service_domain + '/GeoMetrix/Track.svc/RegisterHit';

		var hitdata = 
		'{"AssetType":"' + assetType + '",' + 
		'"HitType":"' + hitType + '",' + 
		'"Url":"' + url + '",' + 
		'"Latitude":' + latitude + ',' +
		'"Longitude":' + longitude + '}';
	
		jQuery.ajax({
			url: 'http://' + geoloc_postproxy_domain + '/Scripts/AppService/PostProxy.ashx?url=' + escape(destinationUrl),
			type: 'POST',
			dataType: 'json',
			data: hitdata,
			contentType: 'application/json; charset=utf-8',
			success: function(result){} 
		});
	}
	
	//top_asset_query wrapper
	function articles_around(latitude, longitude){
		var geoMetrixRect = LocationToArea(latitude, longitude, geoSettings.r);
		top_assets_query('story', 'view', 24, '', geoMetrixRect.latTop, geoMetrixRect.lngRight, geoMetrixRect.latBottom, geoMetrixRect.lngLeft, 10, 'callback_top_assets');
	}
	
	function seeall(){
		document.getElementById("last7").style.display="block";
		jQuery(".seeall").html('<a href="javascript:seeless();">Collapse</a>');
		jQuery(".story_v2_function").animate({ height: jQuery(".story_v2").height() + "px" }, 1000 );
	}

	function seeless(){
		document.getElementById("last7").style.display="none";
		jQuery(".seeall").html('<a href="javascript:seeall();">See all results</a>');
		jQuery(".story_v2_function").animate({ height: jQuery(".story_v2").height() + "px" }, 1000 );
	}
	
	function newLoc(){
		eraseCookie("allowgeo");
		navigator.geolocation.getCurrentPosition (
			function(position) {
				//Get latitude 
				geoSettings.ltd = position.coords.latitude;
				geoSettings.lng = position.coords.longitude;
				createCookie("allowgeo","yes");
				createCookie("geolong",geoSettings.lng);
				createCookie("geolat",geoSettings.ltd);
				//Display aricles red around callers location 
				articles_around(geoSettings.ltd, geoSettings.lng);
				//Register hit
				register_hit_query(geo_link, 'story', 'view', geoSettings.ltd, geoSettings.lng, null);
				jQuery("#location_refresh").animate({ height: "12px" }, 1000);
				setTimeout("selfDestruct();", 3000);
			},
			function() { createCookie("allowgeo","no"); }
		);
	}
	
	function selfDestruct() { jQuery("#location_refresh").animate({ height: "0px" }, 1000); }
	
	//top_assets_query callback on success
	function callback_top_assets(data) {
		var tag = '';
		var tagxin ='';
		var myJSONText = JSON.stringify(data, replacer);
		reverseRadius(data.BoundingBox.Latitude1);
		if (data.Assets.length > 0) {
			//Stories found
			tag = '<div class="radiusarea"><form action="#" onsubmit="changeRadius(); return false;">Stories within <input maxlength="5" type="text" value="'+display_radius+'" class="radius_display" id="setRadius" /> km <input type="image" src="/images/heatmap/radius_submit2.jpg" class="subradius" /></form></div> <div class="clear"></div><div id="geo_error"></div><div class="clear"></div><div class="geolb_story"><div id="first3"><table cellpadding="0" cellspacing="0" border="0" class="list_table">';
			for(var i=0; i < data.Assets.length; i++) {
				var title = data.Assets[i].Title;
				var url = data.Assets[i].Url;
				url = "http://" + geoloc_postproxy_domain + url.substring(url.indexOf(".com")+4);
				//if(url.indexOf("nationalpost.com") < 0) 
				tag = tag + '<tr><td class="story_num_cell" valign="top"><div class="story_num">'+(i+1)+'</div></td><td valign="top"><div class="geolb_story_items"><a href="'+url+'">'+ title + '</a></div></td></tr>';
				if(i==2) tag = tag + '</table></div><div id="last7"><table cellpadding="0" cellspacing="0" border="0" class="list_table">';
			}
		  	tag = tag + '</table></div><div class="seeall"><a href="javascript:seeall();">See all results</a></div></div><div class="newlocation"><a href="javascript:newLoc();">Changed your location?</a></div>';
		}
		else {
			//Stories not found
			story_around_me = '';
			tag = 'No Stories Around Me';
			tagxin = 'No stories around me';
		}
		story_around_me = '<div class="geo_logo"></div>' + tag;
		jQuery(".story_v2").html(story_around_me);
		if(flagit) jQuery("#geo_stories_around").animate({ height: "0px" }, 1000 );
		setTimeout("jQuery('.story_v2_function').animate({ height: jQuery('.story_v2').height() + 'px' }, 1000 );", 1000);
//		geolb.mask(jQuery('body'),geolb.getHtml());
//		if (data.Assets.length < 6) jQuery(".nextprev").css("display","none");
	}

	function replacer(key, value) {
		if (typeof value === 'number' && !isFinite(value)) { return String(value); }
		return value;
	}
	
	//GeoMetrixRectangle
	function GeoMetrixRect(latTop, lngRight, latBottom, lngLeft) {
		this.latTop = latTop;       //Top latitude
		this.lngRight = lngRight;   //Right longitude
		this.latBottom = latBottom; //Bottom latitude
		this.lngLeft = lngLeft;     //Left longitude
	}
	
	//Function LocationToArea converts location (latitude, longitude) in grad
	//and radius in meters into border rectangle(latitudeTop, latitudeBottom, longitudeLeft, longitudeRight)
	//where distance between:
	//latitude and latitudeTop
	//latitude and latitudeBottom
	//longitude and longitudeLeft
	//longitude and longitudeRight
	//is radius (in meters)
	function LocationToArea(latitude, longitude, radius) {
		//Earth radius in meters
		var earthRadius = 6378000;
		//Equator length in meters
		var equatorLength = 2*Math.PI*earthRadius;
		//Parallel length in meters @ latitude 
		//(latitude in grad)    
		var parallelLength = Math.cos(Math.PI/180*latitude)*equatorLength;
		//Grad per meter @ latitude   
		var gradsPerMeter_latitude = 360/parallelLength;
		//Grad per meter @ longitude
		var gradsPerMeter_longitude = 360/equatorLength;
		//Border rectangle difinition
		var latitudeTop = parseFloat(latitude) + radius*gradsPerMeter_longitude;
		var latitudeBottom = parseFloat(latitude) - radius*gradsPerMeter_longitude;
		var longitudeRight = parseFloat(longitude) + radius*gradsPerMeter_latitude;
		var longitudeLeft = parseFloat(longitude) - radius*gradsPerMeter_latitude;
		
		return new GeoMetrixRect(latitudeTop, longitudeRight, latitudeBottom, longitudeLeft);
	}

	function reverseRadius(lat1) {
		var temp1 = 0;
		var temp2 = 0;
		//Equator length in meters
		var equatorLength = 2*Math.PI*6378000;
		//Parallel length in meters @ latitude 
		//(latitude in grad)    
		var parallelLength = Math.cos(Math.PI/180*parseFloat(geoSettings.ltd))*equatorLength;
		//Grad per meter @ latitude   
		var gradsPerMeter_latitude = 360/parallelLength;
		//Grad per meter @ longitude
		var gradsPerMeter_longitude = 360/equatorLength;
		//Border rectangle difinition
		actualRadius = parseInt((parseFloat(lat1) - parseFloat(geoSettings.ltd)) / gradsPerMeter_longitude);
		actualRadiusKM = Math.ceil(actualRadius/1000);
		if(actualRadiusKM == 0) actualRadiusKM = 1;
		if(first_time_check) {
			geoSettings.limit = actualRadiusKM;
			first_time_check = false;
		}
		if(!radiusflag) display_radius = actualRadiusKM;
		temp1 = parseInt((90 - parseFloat(geoSettings.ltd)) / gradsPerMeter_longitude);
		temp2 = Math.abs(parseInt((-90 - parseFloat(geoSettings.ltd)) / gradsPerMeter_longitude));
		if (temp1 < temp2) limitRadius = temp1;
		else limitRadius = temp2;
		limitRadius = parseInt(limitRadius/1000); 
	}

	function changeRadius() {
		var r = parseInt(document.getElementById("setRadius").value);
		radiusflag = false;
		if(r <= 0 || r < geoSettings.limit) {
			jQuery("#geo_error").html("There are not enough stories based on the distance entered. Please provide a distance greater than "+geoSettings.limit+" km");
			jQuery("#geo_error").css("display","block");
			jQuery(".story_v2_function").animate({ height: jQuery(".story_v2").height() + "px" }, 1000 );
		}
		else if(r+"" == "" || r+"" == "NaN") {
			jQuery("#geo_error").html("Please type in a number value only."); 
			jQuery("#geo_error").css("display","block");
			jQuery(".story_v2_function").animate({ height: jQuery(".story_v2").height() + "px" }, 1000 );
		}
		else if(r > limitRadius) {
			display_radius = r;
			radiusflag = true;
			jQuery("#geo_error").css("display","none");
			articles_around(geoSettings.ltd, geoSettings.lng);
		}
		else{
			jQuery("#geo_error").css("display","none");
			geoSettings.r = r * 1000;
			articles_around(geoSettings.ltd, geoSettings.lng);
		}
		document.getElementById("setRadius").value = "";
	}
	
	function noError() { jQuery("#geo_error").css("display","none"); }

	function commas(num) {
		num = num+"";
		if(num.length==6) num = num.substring(0,3) + "," + num.substring(3);
		if(num.length==5) num = num.substring(0,2) + "," + num.substring(2);
		if(num.length==4) num = num.substring(0,1) + "," + num.substring(1);
		return num;
	}

	function scrollIt() {
		if(moveFlag) {
			jQuery(".geo_mover").animate({ top: "-250px" }, 1000 );
			jQuery(".nextprev").css("display","none");
			jQuery(".prevnext").css("display","inline");
			moveFlag = false;
		}
		else {
			jQuery(".geo_mover").animate({ top: "0px" }, 1000 );
			jQuery(".prevnext").css("display","none");
			jQuery(".nextprev").css("display","inline");
			moveFlag = true;
		}
	}
// light box
var geolb={
	getHtml:function(){
	 HTML='<div class="geolb_content">'+
			'<div class="geolb_top"><a class="close_geo" href="javascript:geolb.unmask(jQuery(\'body\')); noError();"><img src="/images/heatmap/close.jpg" alt="Close" /></a><div class="geowrap">Check out the top stories being read right now by<br />people in your neighbourhood and across the country.</div></div>'+
			'<div class="geolb_mid"><div class="change_radius_bar"><div class="change_radius_text"><form action="#" onsubmit="changeRadius(); return false;">Find out what stories are being read within&nbsp;&nbsp;<input type="text" maxlength="6" id="setRadius" />&nbsp;&nbsp;km around you.</form></div> <a href="javascript:changeRadius();"><img src="/images/heatmap/radius_submit.jpg" alt="Submit" /></a></div>'+
			'<div id="geo_error"></div>'+story_around_me+'<a class="nextprev" href="javascript:scrollIt();"><img src="/images/heatmap/next.gif" alt="Next 5" /></a><a class="prevnext" href="javascript:scrollIt();"><img src="/images/heatmap/prev.gif" alt="Previous 5" /></a></div>'+
		  '</div>';
	 return HTML;
	 },
	getHtmlLearn:function(){
	 HTMLlearn='<div class="geolb_content">'+
			'<div class="geolb_top"><a class="close_geo" href="javascript:geolb.unmask(jQuery(\'body\'));"><img src="/images/heatmap/close.jpg" alt="Close" /></a><div class="geowrap">Check out the top stories being read right now by<br />people in your neighbourhood and across the country.</div></div>'+
			'<div class="geolb_learn_body"><div class="learn_left f-left"><div class="learnwrap"><h1>Why are we asking you to share your location with us?</h1><ul class="learnbullet nobullet"><li>We want to provide you with the most relevant local stories.</li></ul>'+
			'<h1>Keep in mind that your location is kept private.<br />We will NOT:</h1><ul class="learnbullet"><li>Share your location with advertisers</li><li>Display your personal location publically</li><li>Link your location to your personal profile</li></ul>'+
			'<div class="learn_button"><a href="javascript:show_geo_stories(); geolb.unmask(jQuery(\'body\'));" class="share-button"><img src="/images/heatmap/sharebutton_learn.jpg" alt="Share your location" class="sharebutton" /></a></div>'+
			'</div></div><img src="/images/heatmap/learn.jpg" alt="" /></div>'+
			'</div>';
	 return HTMLlearn;
	 },
	// content of box
	
	//unmask start
	unmask:function(myOb){ 
		myOb.find(".loadmask-msg,.loadmask").remove();
		myOb.removeClass("masked");
		myOb.removeClass("masked-relative");
		myOb.find("select").removeClass("masked-hidden")
	},
	//unmask end

	//mask start
	mask:function(myOb,c){
		geolb.unmask(myOb);
		if(myOb.css("position")=="static"){	myOb.addClass("masked-relative")}
		myOb.addClass("masked");
		var d=jQuery('<div class="loadmask" onclick="geolb.unmask(jQuery(\'body\'));"></div>');
		
		if(navigator.userAgent.toLowerCase().indexOf("msie")>-1){
			d.height(myOb.height()+parseInt(myOb.css("padding-top"))+parseInt(myOb.css("padding-bottom")));	
			d.width(myOb.width()+parseInt(myOb.css("padding-left"))+parseInt(myOb.css("padding-right")))
		}
		if(navigator.userAgent.toLowerCase().indexOf("msie 6")>-1){ myOb.find("select").addClass("masked-hidden") }
		myOb.append(d);

		var viewportwidth;
		var viewportheight;
		if (typeof window.innerWidth != 'undefined'){
		  viewportwidth = window.innerWidth,
		  viewportheight = window.innerHeight
		}
		else if (typeof document.documentElement != 'undefined' && typeof document.documentElement.clientWidth != 'undefined' && document.documentElement.clientWidth != 0){
		   viewportwidth = document.documentElement.clientWidth,
		   viewportheight = document.documentElement.clientHeight
		}
		else {
		   viewportwidth = document.getElementsByTagName('body')[0].clientWidth,
		   viewportheight = document.getElementsByTagName('body')[0].clientHeight
		}

		if(typeof c=="string"){
			var b=jQuery('<div class="loadmask-msg" style="display:none;"></div>');			
			b.append("<div>"+c+"</div>");			
			myOb.append(b);
			b.css("top",Math.round(viewportheight/2-(b.height()-parseInt(b.css("padding-top"))-parseInt(b.css("padding-bottom")))/2)-50+"px");			
			b.css("left",Math.round((viewportwidth/2-(b.width()-parseInt(b.css("padding-left"))-parseInt(b.css("padding-right")))/2)-40)+"px");			
			b.show()
		}
	}
	//end mask
}; // end of geolb