// Javascript functions for the Default.aspx page
// Author: Lewis Harvey
// Date: January 2007
var currentShowingIcon = null;
var TEMP_PIN_ID = 4000;
var ADD_PIN_ID = 3999;
var numberOfContentItems = 0;
var contentItemMoveFirstTime = true;
var homeLocationLatitude;
var homeLocationLongitude;
var homeLocationZoom;
var isHomeLocation = false;

function Guid()
{
    var result, i, j;
    result = '';
    for(j=0; j<32; j++)
    {
        if( j == 8 || j == 12|| j == 16|| j == 20)
            result = result + '-';
        i = Math.floor(Math.random()*16).toString(16).toUpperCase();
        result = result + i;
    }
    return result;
}

function MapMouseClick(e)
{
	/*if (event.button==2) {
		if(map.GetMapMode() == VEMapMode.Mode2D)
		{
			if(currentShowingIcon != null)
				map.DeletePushpin(currentShowingIcon);
			var latLong = map.PixelToLatLong(event.x-5,event.y-5, map.GetZoomLevel());
			var tempPin = new VEPushpin(
				ADD_PIN_ID, 
				latLong, 
				"images/target.gif", 
				'', 
				'<h4>map tools</h4><a href=\"GeoTagContent.aspx?lat=' + latLong.Latitude + '&lon=' + latLong.Longitude + '\">Add Content Here</a>'
				);
 
			map.AddPushpin(tempPin);
			currentShowingIcon = ADD_PIN_ID;
		}
	}*/
	
	if (e.rightMouseButton) {
		if(map.GetMapMode() == VEMapMode.Mode2D)
		{
			try
			{
				if(currentShowingIcon != null)
					map.DeleteShape(map.GetShapeByID(currentShowingIcon));
			}
			catch(e) {}
			var latLong = map.PixelToLatLong(new VEPixel(e.mapX,e.mapY));
			/*var tempPin = new VEPushpin(
				ADD_PIN_ID, 
				latLong, 
				"images/target.gif", 
				'', 
				'<h4>map tools</h4><a href=\"GeoTagContent.aspx?lat=' + latLong.Latitude + '&lon=' + latLong.Longitude + '\">Add Content Here</a>'
				);*/
			var tempPin = new VEShape(VEShapeType.Pushpin,  latLong);
			tempPin.SetTitle("<h4>map tools</h4>");
			tempPin.SetDescription("<a href=\"GeoTagContent.aspx?lat=" + latLong.Latitude + "&lon=" + latLong.Longitude + "\">Add Content Here</a>");
			tempPin.SetCustomIcon("images/target.gif");
 			map.AddShape(tempPin);
			currentShowingIcon = tempPin.GetId();
		}
	}
} 


function MapLoad(e)
{
    setTimeout("MapChange()", 1000);
    //if(msieversion() == 7)
        //RemoveBlack('myMap');
}

// This function returns Internet Explorer's major version number,
// or 0 for others. It works by finding the "MSIE " string and
// extracting the version number following the space, up to the decimal
// point, ignoring the minor version number
function msieversion()
{
    var ua = window.navigator.userAgent
    var msie = ua.indexOf ( "MSIE " )

    if ( msie > 0 )      // If Internet Explorer, return version number
        return parseInt (ua.substring (msie+5, ua.indexOf (".", msie )))
    else                 // If another browser, return 0
        return 0

}

function MapChange()
{
   // if(msieversion() == 7)
   { 
      //  RemoveBlack('myMap');
        //alert("ie7");
        }
  
  if (itemid != null)
  {
        //MapChangeService.GetItem(itemid, ItemsReceived);
        getItem(itemid);
  }      
  else
  {
        var mapStyle = map.GetMapStyle();
        if (mapStyle != "o")
        {
            // Get the JSON
            getItems();
        }
  }
}

function MapEndZoom(e)
{
    //RemoveBlack('myMap');
}


function ItemsReceived(contentItems, isHomeLocation)
{

    /*DeleteAllUserPushpins();
   
    var imageBarHtml = "<div id=\"imageBarImages\" style=\"position: relative; height: 105px;\">";
    imageBarHtml += "<table cellpadding=\"0\" cellspacing=\"0\"><tr>";
    
    // Loop adn draw the pins
   numberOfContentItems = contentItems.Items.length; 
   var collection = new Array();
   var itemCount = contentItems.Items.length;
    for(var i = 0; i < contentItems.Items.length;  i++)
    {
	var contentItem = contentItems.Items[i];
	var description = "";
	description += "<a href=\"" + contentItem.Link + "\" target=\"_blank\"><img src=\"" + contentItem.ThumbnailLink + "\" align=\"right\" border=\"0\" width=\"96px\" height=\"96px\" style=\"padding-left: 5px; padding-bottom: 5px;\"></a>" + contentItem.Description + "<br /><br />";
	description += "<div style=\"clear: both;\">find similar: ";
	var tagList = "";
	for(var j = 0; j < contentItem.Tags.length; j++)
	{
		tagList += "<a href=\"map.aspx?tags=" + contentItem.Tags[j].TagName + "\">" + contentItem.Tags[j].TagName + "</a>,";
	}
	description += tagList.substring(0, tagList.length - 1);
	description += "</div><br />";
	description += "<h4>tools</h4>";
	description += "<a href=\"" + contentItem.Link + "\" target=\"_blank\">view content</a><br />";
	description += "<a href=\"#\" onclick=\"map.SetCenterAndZoom(new VELatLong(" + contentItem.Lat + ", " + contentItem.Long + "), 16);\">zoom to street level</a><br />";
	description += "<a href=\"#\" onclick=\"map.SetCenterAndZoom(new VELatLong(51.528, 0.02), 12);\">reset map</a><br />";
	description += "<a href=\"ReportAbuse.aspx?contentItemId=" + contentItem.ContentItemId + "\">report abuse</a>";
	var icon = "images/icons/icon.png";
	if(msieversion() != 7 && msieversion() != 0)
		icon = "images/icons/icon.gif";
    
	var pinLatLong = new VELatLong(contentItem.Lat,contentItem.Long)
	var pin = new VEPushpin(pinID++, pinLatLong, icon , contentItem.Title, description);
	map.AddPushpin(pin);  
	collection[i] = pinLatLong;
        
        // Now generate image for image bar
        imageBarHtml += "<td>";
        var margin = "";
        if(i > 0)
		margin = "margin-left: 5px;";
        imageBarHtml += "<div class=\"contentItemContainer\" onmouseover=\"this.className = 'highlightedContentItemContainer';\" onmouseout=\"this.className = 'contentItemContainer';\" style=\"width: 96px; height: 96px; " + margin + " \">";
        imageBarHtml += "<a href=\"#\" title=\"view this content\"><img src=\"" + contentItem.ThumbnailLink + "\" border=\"0\" width=\"96px\" height=\"96px\" onmouseover=\"HighlightItem(" + i + ");\" onmouseout=\"UnhighlightItem(" + i + ");\" onclick=\"map.SetCenterAndZoom(new VELatLong(" + contentItem.Lat + ", " + contentItem.Long + "), 16);\" /></a>";
        imageBarHtml += "</div>";
        imageBarHtml += "</td>";
        
        
    }
    
	if(contentItemMoveFirstTime && contentItems.Items.length == 1)
	{
		map.DetachEvent("onchangeview", MapChange);
		map.DetachEvent("onendzoom", MapEndZoom);
		map.SetMapView(collection); 
		map.SetZoomLevel(15);
		map.AttachEvent("onchangeview", MapChange);
		map.AttachEvent("onendzoom", MapEndZoom);
		contentItemMoveFirstTime = false;
	}
   
   // Searched Bar
        var searchedBarHtml = "You are viewing the 50 most recent items.";
        
        if(search != "false")
        {
		searchedBarHtml = "You searched for '" + search + "', " + itemCount + " items of information found.";
        }
        else
        {
                if(queryString("tags") != "false")
		{
			searchedBarHtml = "You are viewing '" + queryString("tags") + "', " + itemCount + " items of information found.";
		}
	}
        
        $('searchedPanel').innerHTML = searchedBarHtml;
   imageBarHtml += "</tr></table></div>"; 
   
   
   
   $('mostPopularInnerContainer').innerHTML = imageBarHtml;   
   
   */
   
    map.DeleteAllShapes();
    var imageBarHtml = "<div id=\"imageBarImages\" style=\"position: relative; height: 105px;\">";
    imageBarHtml += "<table cellpadding=\"0\" cellspacing=\"0\"><tr>";
    
    // Loop adn draw the pins
   numberOfContentItems = contentItems.Items.length; 
   var collection = new Array();
   var itemCount = contentItems.Items.length;
    for(var i = 0; i < contentItems.Items.length;  i++)
    {
	var contentItem = contentItems.Items[i];
	var description = "";
	description += "<a href=\"" + contentItem.Link + "\" target=\"_blank\"><img src=\"" + contentItem.ThumbnailLink + "\" align=\"right\" border=\"0\" width=\"96px\" height=\"96px\" style=\"padding-left: 5px; padding-bottom: 5px;\"></a>" + contentItem.Description + "<br /><br />";
	description += "<div style=\"clear: both;\">find similar: ";
	var tagList = "";
	for(var j = 0; j < contentItem.Tags.length; j++)
	{
		tagList += "<a href=\"map.aspx?tags=" + contentItem.Tags[j].TagName + "\">" + contentItem.Tags[j].TagName + "</a>,";
	}
	description += tagList.substring(0, tagList.length - 1);
	description += "</div><br />";
	description += "<h4>tools</h4>";
	description += "<a href=\"" + contentItem.Link + "\" target=\"_blank\">view content</a><br />";
	description += "<a href=\"#\" onclick=\"map.SetCenterAndZoom(new VELatLong(" + contentItem.Lat + ", " + contentItem.Long + "), 16);\">zoom to street level</a><br />";
	description += "<a href=\"#\" onclick=\"map.SetCenterAndZoom(new VELatLong(51.528, 0.02), 12);\">reset map</a><br />";
	description += "<a href=\"ReportAbuse.aspx?contentItemId=" + contentItem.ContentItemId + "\">report abuse</a><br />";
	//description += "<a href=\"ViewComments.aspx?contentItemId=" + contentItem.ContentItemId + "\">view comments</a>";
	var icon = "images/icons/icon.png";
	if(msieversion() != 7 && msieversion() != 0)
		icon = "images/icons/icon.gif";
    
	var pinLatLong = new VELatLong(contentItem.Lat,contentItem.Long)
	var pin = new VEShape(VEShapeType.Pushpin, pinLatLong);
	pin.SetTitle(contentItem.Title);
	pin.SetDescription(description);
	pin.SetCustomIcon(icon);
	map.AddShape(pin);
	collection[i] = pinLatLong;
        
        // Now generate image for image bar
        imageBarHtml += "<td>";
        var margin = "";
        if(i > 0){
		margin = "margin-left: 5px;";}
        imageBarHtml += "<div class=\"contentItemContainer\" onmouseover=\"this.className = 'highlightedContentItemContainer';\" onmouseout=\"this.className = 'contentItemContainer';\" style=\"width: 96px; height: 96px; " + margin + " \">";
        imageBarHtml += "<a href=\"#\" title=\"view this content\"><img src=\"" + contentItem.ThumbnailLink + "\" border=\"0\" width=\"96px\" height=\"96px\" onmouseover=\"HighlightItem('" + pin.GetID() + "');\" onmouseout=\"UnhighlightItem('" + pin.GetID() + "');\" onclick=\"map.SetCenterAndZoom(new VELatLong(" + contentItem.Lat + ", " + contentItem.Long + "), 16);\" /></a>";
        imageBarHtml += "</div>";
        imageBarHtml += "</td>";
        
        // Process the Delete shape
        
        
    }
    
	if((contentItemMoveFirstTime && contentItems.Items.length == 1 && isHomeLocation == false))
	{
		map.DetachEvent("onchangeview", MapChange);
		map.DetachEvent("onendzoom", MapEndZoom);
		map.SetMapView(collection); 
		map.SetZoomLevel(15);
		map.AttachEvent("onchangeview", MapChange);
		map.AttachEvent("onendzoom", MapEndZoom);
		contentItemMoveFirstTime = false;
	}
	
	isHomeLocation = false;
   
   // Searched Bar
   //     var searchedBarHtml = "You are viewing the 50 most recent items.";
        
   //     if(search != "false")
   //     {
	//	searchedBarHtml = "You searched for '" + search + "', " + itemCount + " items of information found.";
    //    }
    //    else
    //    {
     //           if(queryString("tags") != "false")
	//	{
	////		searchedBarHtml = "You are viewing '" + queryString("tags") + "', " + itemCount + " items of information found.";
	//	}
	//}
        
        //$('searchedPanel').innerHTML = searchedBarHtml;
   imageBarHtml += "</tr></table></div>"; 
   
   
   
   $('mostPopularInnerContainer').innerHTML = imageBarHtml;   
   
   
   
}

function MoveImageBar(direction)
{
	if($('imageBarImages') == null)
		return;
	var amountToMove = 500;
	if(direction == "left")
	{
		var totalPixelsForBar = (numberOfContentItems * 100) - 200;
		if(($('imageBarImages').style.pixelLeft % amountToMove) == 0 && $('imageBarImages').style.pixelLeft > -totalPixelsForBar) 
		new Effect.MoveBy('imageBarImages', 0, -amountToMove);
	}
	else
	{
		if(($('imageBarImages').style.pixelLeft % amountToMove) == 0 && $('imageBarImages').style.pixelLeft < 0) 
		new Effect.MoveBy('imageBarImages', 0, amountToMove);
	}
}

/*function HighlightItem(i)
{
	try
	{
		UnhighlightItem();
	}
	catch(e)
	{}
	var pin = map.pushpins[i];
	var latLong = new VELatLong(pin.LatLong.Latitude + 0.00001, pin.LatLong.Longitude-0.00001);
	var icon_large = "images/icons/icon_large.png";
	if(msieversion() != 7 && msieversion() != 0)
		icon_large = "images/icons/icon_large.gif";
	var pin2 = new VEPushpin(TEMP_PIN_ID, latLong, icon_large , pin.Title, pin.Details);
	map.AddPushpin(pin2);  
	document.getElementById(TEMP_PIN_ID + "_" + map.GUID).onmouseover();
}

function UnhighlightItem()
{
	document.getElementById(TEMP_PIN_ID + "_" + map.GUID).onmouseout();
	map.DeletePushpin(TEMP_PIN_ID);
}*/

function HighlightItem(pinId)
{
	map.HideInfoBox();
	try
	{
		UnhighlightItem(pinId);
	}
	catch(e)
	{}
	var pin = map.GetShapeByID(pinId);
	var icon_large = "images/icons/icon_large.png";
	if(msieversion() != 7 && msieversion() != 0)
		icon_large = "images/icons/icon_large.gif";
	pin.SetCustomIcon(icon_large);
	var pixels = map.LatLongToPixel(pin.GetPoints()[0]);
	map.ShowInfoBox(pin, pin.GetPoints()[0], new VEPixel(20, 5));
}

function UnhighlightItem(pinId)
{
	var pin = map.GetShapeByID(pinId);
	var icon = "images/icons/icon.png";
	if(msieversion() != 7 && msieversion() != 0)
		icon = "images/icons/icon.gif";
	pin.SetCustomIcon(icon);
}


function GenerateBookmark()
{
	var url = "map.aspx?";
	
	// Process map.
	var zoomLevel = map.GetZoomLevel();
	var tags = queryString("tags");
	var creator = queryString("creator");
	var search = queryString("search");	
	var center = map.GetCenter();
	
	url = url + "zoom=" + zoomLevel;
	url = url + "&lat=" + center.Latitude;
     url = url + "&long=" + center.Longitude;
     
     var mapStyle = map.GetMapStyle();
     url = url + "&style=" + mapStyle.substr(0, 1);
     
	if(tags != "false")
		url = url + "&tags=" + tags;
	
	if(creator != "false")
        url = url + "&creator=" + creator;
	
	if(search != "false")
        url = url + "&search=" + search;
     
	
	window.location = url;
}

function GoToHomeLocation()
{
	//window.location = url;
	var wRequest2 = new Sys.Net.WebRequest();
    // Set the request URL.      
    var url = "useraccounts/homelocation.aspx?action=GET&random=" + new Date().toString();
    wRequest2.set_url(url);

    // Set the request verb.
    wRequest2.set_httpVerb("GET");
           
    // Set the request callback function.
    wRequest2.add_completed(OnWebRequestCompleted2);
 
    // Execute the request.
    wRequest2.invoke();
}

// This callback function processes the request return values. It is called asynchronously by the current executor.
function OnWebRequestCompleted2(executor, eventArgs) 
{    
    if(executor.get_responseAvailable()) 
    {
            var location = eval('(' + executor.get_responseData() +')');
            isHomeLocation = true;
            map.SetCenter(new VELatLong(location.HomeLatitude,location.HomeLongitude));
    }
}

function SetHomeLocation()
{
	var center = map.GetCenter();
    homeLocationLatitude = center.Latitude;
    homeLocationLongitude = center.Longitude;

	//window.location = url;
	var wRequestSetLocation = new Sys.Net.WebRequest();
    // Set the request URL.      
    var url = "useraccounts/homelocation.aspx?random=" + new Date().toString() + "&action=SET&homeLatitude=" + homeLocationLatitude + "&homeLongitude=" + homeLocationLongitude;
    wRequestSetLocation.set_url(url);

    // Set the request verb.
    wRequestSetLocation.set_httpVerb("GET");
           
    // Set the request callback function.
    wRequestSetLocation.add_completed(OnWebRequestCompletedSetLocation);
 
    // Execute the request.
    wRequestSetLocation.invoke();
}

// This callback function processes the request return values. It is called asynchronously by the current executor.
function OnWebRequestCompletedSetLocation(executor, eventArgs) 
{    
	window.location = "map.aspx?lat=" + homeLocationLatitude + "&long=" + homeLocationLongitude + "&zoom=16&style=a";
}

function encode(text) {
	var encodedHtml = escape(text);
	encodedHtml = encodedHtml.replace(/\//g,"%2F");
	encodedHtml = encodedHtml.replace(/\?/g,"%3F");
	encodedHtml = encodedHtml.replace(/=/g,"%3D");
	encodedHtml = encodedHtml.replace(/&/g,"%26");
	encodedHtml = encodedHtml.replace(/@/g,"%40");
	return encodedHtml;
} 