function set_cookie ( name, value, exp_y, exp_m, exp_d, path, domain, secure )	{
	  var cookie_string = name + "=" + escape ( value );
	  if ( exp_y ){
		var expires = new Date ( exp_y, exp_m, exp_d );
		cookie_string += "; expires=" + expires.toGMTString();
	  }
    	cookie_string += "; path=" + escape ( path );
	  if ( domain )
			cookie_string += "; domain=" + escape ( domain );
	  if ( secure )
			cookie_string += "; secure";
	  document.cookie = cookie_string;
	}

function readCookie(cookieName) {
	 var theCookie=""+document.cookie;
	 var ind=theCookie.indexOf(cookieName);
	 if (ind==-1 || cookieName=="") return ""; 
	 var ind1=theCookie.indexOf(';',ind);
	 if (ind1==-1) ind1=theCookie.length; 
	 return unescape(theCookie.substring(ind+cookieName.length+1,ind1));
}

// Facebook share
function fbs_click(){
	u=location.href;
	t=document.title;
	window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(u)+'&t='+encodeURIComponent(t),'sharer','toolbar=0,status=0,width=626,height=436');
}



function authUser(){
	$("#fbauthor").html( 
		"<div id=\"fb_user\"><fb:profile-pic size='square' uid='loggedinuser' facebook-logo='true'></fb:profile-pic>"
		+ "<p style=\"margin-top:10px; width:180px; float:left;\"><b style=\"font-weight:normal; font:12px Arial, Helvetica, sans-serif;\">Welcome, <fb:name useyou='false'  uid='loggedinuser'></fb:name>.</b>"
		+ "<br />You are signed in with your facebook account. <a href=\"javascript:FB.Connect.logout(refresh_page);\" onclick=\"\">Sign-Out</a>.</p></div>"
		+ "<input type=\"hidden\" name=\"fbuser\" id=\"fbuser\" value=\"1\" />");
	//$('#fbconnect').hide();
	FB.XFBML.Host.parseDomTree();
}


function init_map(){

	// Init Map
	//var map = new GMap2(document.getElementById('map'));
	var bounds = new GLatLngBounds();
	
	// Set Map UI
	var customUI = map.getDefaultUI();
	customUI.controls.maptypecontrol = false;
	customUI.controls.scalecontrol = false;
	customUI.maptypes.physical =false;
	map.setUI(customUI);

	// Set up our GMarkerOptions object literal
	// Set zoom variance, not actual value
	var zoomLevel = -2;
	// Load Initial data

/*
				// Build Marker
				var tinyIcon = new GIcon();
				tinyIcon.image = "http://cityinstant.com/public/assets/images/_markers/green/blank.png";
				tinyIcon.shadow = "/public/assets/images/_markers/shadow.png";
				tinyIcon.iconSize = new GSize(20, 34);
				tinyIcon.shadowSize = new GSize(38,36);
				tinyIcon.iconAnchor = new GPoint(6, 20);
				tinyIcon.infoWindowAnchor = new GPoint(5, 1);
				var markerOptions = { icon:tinyIcon };
	
	
	$.getJSON("/items/recent/30", function(json) {
	
		if (json.Locations.length > 0) {

			$(json.Locations).each(function(this_index,location){
				
				// Init
				var item_ID = $(this);
				var points = $(this).attr('rel');
				var dom_id = $(this).attr('id');
				if(!points) return true;
				
				
				// Add Marker
				points = points.split(',');
				var point = new GLatLng(location.lat,location.lon);		
				var marker = new GMarker(point,markerOptions);
				map.addOverlay(marker);
				bounds.extend(marker.getPoint());
				GEvent.addListener(marker, "click", function(){
					displayPoint(map, marker, location.description);
				});
			});
		}
	})
*/
	
	map.setCenter(new GLatLng(35.15344,-80.88613));
	map.setZoom(11);
	
	start_update_cycle();
	
	return true;
}

function start_update_cycle(){
	var start_from = (last_update_id) ? last_update_id : '';
	$.getJSON("/items/recent/30/"+start_from, function(json) {
		if (json.Locations.length > 0) {
			new_updates = json;
			new_updates_max = json.Locations.length;
			update_stream();
			return true;
		}
	});
}

function update_stream(){
	
/*
	Good Morning Wuori!
	This is past Wuori, I am writing future you from last night to remind you
	that if we're going to remove markers after a certain number are displayed,
	then we need a different iterator. Since we're not displaying the stream div
	anymore, we can start from 0 again instead of relying on item.ID as the increment value.
	
	Also, don't forget to email your sister and call momma.

	
	if(total_counter > 80){
		// Start clearing off some updates, say like 10 at a time
		map.removeOverlay(markers[item_ID]); 
	}
*/
	
	/* Build Markers */
	var markerOptions = new Array();
	
	// -- Twitter
	var marker_3 = new GIcon();
	marker_3.image = "http://cityinstant.com/public/assets/images/_markers/marker_3.png";
	marker_3.shadow = "/public/assets/images/_markers/shadow.png";
	marker_3.iconSize = new GSize(20, 34);
	marker_3.shadowSize = new GSize(38,36);
	marker_3.iconAnchor = new GPoint(6, 20);
	marker_3.infoWindowAnchor = new GPoint(5, 1);
	markerOptions[3] = { icon:marker_3 };
	
	// -- FourSquare
	var marker_4 = new GIcon();
	marker_4.image = "http://cityinstant.com/public/assets/images/_markers/marker_4.png";
	marker_4.shadow = "/public/assets/images/_markers/shadow.png";
	marker_4.iconSize = new GSize(20, 34);
	marker_4.shadowSize = new GSize(38,36);
	marker_4.iconAnchor = new GPoint(6, 20);
	marker_4.infoWindowAnchor = new GPoint(5, 1);
	markerOptions[4] = { icon:marker_4 };

	// -- Flickr
	var marker_5 = new GIcon();
	marker_5.image = "http://cityinstant.com/public/assets/images/_markers/marker_5.png";
	marker_5.shadow = "/public/assets/images/_markers/shadow.png";
	marker_5.iconSize = new GSize(20, 34);
	marker_5.shadowSize = new GSize(38,36);
	marker_5.iconAnchor = new GPoint(6, 20);
	marker_5.infoWindowAnchor = new GPoint(5, 1);
	markerOptions[5] = { icon:marker_5 };

	// -- YouTube
	var marker_8 = new GIcon();
	marker_8.image = "http://cityinstant.com/public/assets/images/_markers/marker_8.png";
	marker_8.shadow = "/public/assets/images/_markers/shadow.png";
	marker_8.iconSize = new GSize(20, 34);
	marker_8.shadowSize = new GSize(38,36);
	marker_8.iconAnchor = new GPoint(6, 20);
	marker_8.infoWindowAnchor = new GPoint(5, 1);
	markerOptions[8] = { icon:marker_8 };

	// Set up our GMarkerOptions object literal
	// Set zoom variance, not actual value
	// Load Initial data
	if(update_counter == new_updates_max){
		clearTimeout(update_timer);
		update_counter = 0;
		start_update_cycle();
		return false;
	}	
	
	// Init
	var location = new_updates.Locations[update_counter];
	if(!location.lat) return true;
	var item_ID = location.ID;

	// Add Marker
	//var markerType = ;
	var point = new GLatLng(location.lat,location.lng);		
	var marker = new GMarker(point,markerOptions[location.type]);
	if(marker) markers[item_ID] = marker;
	map.addOverlay(markers[item_ID]);
	displayPoint(map, markers[item_ID], location.description);
	GEvent.addListener(markers[item_ID], "click", function(){
		displayPoint(map, markers[item_ID], location.description);
	});
		
	update_counter++;
	total_counter++;
	last_update_id = item_ID;
	
	// Again!
	update_timer = setTimeout("update_stream()",4500);
	
	return true;
			
}

function displayPoint(map, marker, html){
	$("#message").hide();
	var moveEnd = GEvent.addListener(map, "moveend", function(){
		var markerOffset = map.fromLatLngToDivPixel(marker.getLatLng());
		$("#message")
			.html(html)
			.fadeIn()
			.css({ top:markerOffset.y-118, left:markerOffset.x-113 });
		GEvent.removeListener(moveEnd);
	});
	if(autopan) map.panTo(marker.getLatLng());
	return true;
}


/* Init Map */
var markers = [];
var update_counter = 0;
var new_updates = '';
var map = '';
var update_timer = 0;
var total_counter = 0;
var last_update_id = '';
var new_updates_max = 0;
var tail_end = 0;
var autopan = true;


// jQuery - Hide/Show Map
$(document).ready(function() {

	// Locations Map
	if($('#map').length>0){

		// Init Map
/*
		map = new GMap2(document.getElementById('map'));
		map.setCenter(new GLatLng(35.15344,-80.88613));
		map.setZoom(11);
		
		// Set Map UI
		var customUI = map.getDefaultUI();
		customUI.controls.maptypecontrol = false;
		customUI.controls.scalecontrol = false;
		customUI.maptypes.physical =false;
		map.setUI(customUI);
		
		// Add Some Magic
		$("#message").appendTo(map.getPane(G_MAP_FLOAT_SHADOW_PANE));
		//$("#pan_toggle").appendTo(map.getPane(G_MAP_FLOAT_SHADOW_PANE));

		// Load first
		update_stream();	
*/

	$('#map').mapWrapper();



	}
	
	$('#pan_toggle').click(function(){
		if($(this).hasClass('disable')){
			autopan = false;
			$(this).toggleClass('disable').html('Enable Auto-Pan');
			//map.setCenter(new GLatLng(35.15344,-80.88613));
		}else{
			autopan = true;
			$(this).toggleClass('disable').html('Disable Auto-Pan');
		}
		return false;		
	});

	if($('#fbauthor').length>0){
		FB_RequireFeatures(["XFBML"], function() {
			FB.init(
				$('div#fbauthor').attr('rel'),
				"/public/ext/xd_receiver.htm",
				{
				ifUserConnected: function(uid) {
					authUser();
					$('#fbconnect').hide();
				},
				ifUserNotConnected: function() {
					$('#fbconnect').show();
				}
			})
		})
	}
			
	// Anchor Form Submit
	$('a.fs').click(function(){
		$(this).parents('form').submit();	
		return false;
	});

	// Toggle	
	$(".toggler").click(function(){
		obj = $(this).attr("rel");
		$('#'+obj).slideToggle("fast");
		if($(this).hasClass('hor')) $(this).fadeOut();
		return false;
	});
	

});


