/**
PUSHPIN
*/

var MaxRating = 5;

function PushPin(_lat, _lng, _address)
{
	this.mapPoint = new MapPoint(_lat, _lng, _address, false, this);
	this.gMarker = null;
	this.gPoint = null;
	this.gDir = null;
	this.tinyIcon = null;
	this.rating = 0;
	this.visible = false;
	this.showPending = false;
	this.startTime = '';
	this.endTime = '';

	this.street = '';
	this.city = '';
	this.state = '';
	this.zip = '';
	this.country = '';

	this.cachedMyLocation = '';
	this.cachedDistance = '';

	this.nodeId = -1;
	try
	{
		this.ComputeDistance(desimap_GetMyLocation());	
	}
	catch (err)
	{
	}
}

PushPin.prototype.mapPoint;
PushPin.prototype.name;
PushPin.prototype.description;
PushPin.prototype.rating;
PushPin.prototype.phNum;
PushPin.prototype.category;
PushPin.prototype.subcategory;
PushPin.prototype.url;
PushPin.prototype.xmlData;
PushPin.prototype.visible;
PushPin.prototype.nodeId;
PushPin.prototype.street;
PushPin.prototype.city;
PushPin.prototype.state;
PushPin.prototype.zip;
PushPin.prototype.country;

PushPin.prototype.startTime;
PushPin.prototype.endTime;

PushPin.prototype.cachedMyLocation;
PushPin.prototype.cachedDistance;

PushPin.prototype.gMarker;
PushPin.prototype.gPoint;
PushPin.prototype.gDir;
PushPin.prototype.tinyIcon;
PushPin.prototype.iconImagePath;
PushPin.prototype.myTableRow;

PushPin.prototype.showPending;

PushPin.prototype.Show = function()
{
	if(this.mapPoint.lat == -1000 || this.mapPoint.lng  == -1000)
	{
		this.showPending = true;
		return 0;
	}

	gMap.addOverlay(this._getNewMarker());
	//this.gMarker.setImage(moduleBasePath + "/images/icon_orange.png");
	this.showPending = false;
	this.visible = true;
	this._ShowTableRow();
}

PushPin.prototype._ShowTableRow = function()
{
	try
	{
		var parentTd = document.getElementById('idTdItemsCol');
		if(parentTd != null && parentTd != 'undefined')
		{
			parentTd.style.display='block';
		}
	}
	catch (err1)
	{
		alert(err1);
	}


	try
	{
		if(this.myTableRow == null)
		{
			var me=this;
			var itemTable = document.getElementById('idTableItems');
			var iconHtml = "<img width='8px' height='10px' src='" + moduleBasePath + "/images/" + this.iconImagePath + "'></img>";
			var insertIndex = _desimap_GetInsertIndex(itemTable, this.name, this.city, this.cachedDistance, iconHtml);

			var newRow = itemTable.insertRow(insertIndex);
			newRow.className = 'ItemTableRow';
			newRow.onclick = function()
			{
				me._getNewMarker().openInfoWindowHtml(me._getInfoWindowHtml());
			}

			var cell0 = newRow.insertCell(0);
			cell0.className = 'ItemTableCol0';
			cell0.innerHTML=iconHtml; //"<img width='8px' height='10px' src='" + moduleBasePath + "/images/" + this.iconImagePath + "'></img>";

			var cell1 = newRow.insertCell(1);
			cell1.className = 'ItemTableCol1';
			cell1.innerHTML=this.name;

			var cell2 = newRow.insertCell(2);
			cell2.className = 'ItemTableCol2';
			//cell2.innerHTML=trim(this.street) + ", " + trim(this.city) + ", " + trim(this.state) + " " + trim(this.zip);// + ", " + trim(this.country);
			cell2.innerHTML=trim(this.city) + ", " + trim(this.state);

			var cell3 = newRow.insertCell(3);
			cell3.className = 'ItemTableCol3';
			cell3.innerHTML=this.phNum;

			var cell4 = newRow.insertCell(4);
			cell4.className = 'ItemTableCol4';
			cell4.innerHTML=this.cachedDistance;// + ' mi';

			this.myTableRow = newRow;
		}
	}
	catch (err2)
	{
		alert(err2);
	}
}

PushPin.prototype._getNewMarker = function() 
{
	if(this.tinyIcon == null)
	{
		this.tinyIcon = new GIcon();
		this.tinyIcon.image = moduleBasePath + "/images/" + this.iconImagePath;
		//this.tinyIcon.shadow = moduleBasePath + "/images/shadow.png";
		this.tinyIcon.iconSize = new GSize(20, 36);
		//this.tinyIcon.shadowSize = new GSize(22, 20);
		this.tinyIcon.iconAnchor = new GPoint(10, 36);
		this.tinyIcon.infoWindowAnchor = new GPoint(15, 10);
	}

	if(this.gMarker == null)
	{
		if(this.gPoint == null)
		{
			this.gPoint = new GLatLng(this.mapPoint.lat, this.mapPoint.lng, false);
		}
		this.gMarker = new GMarker(this.gPoint, {icon : this.tinyIcon});

		//this.gMarker = new GMarker(this.gPoint);
		var me=this;
		GEvent.addListener(this.gMarker, "mouseover", function() {
			try
			{
				if(textBoxFocussedFlag == true)
				{
					document.getElementById('idTxtMyLocation').blur();
				}
			}
			catch (err_)
			{
				alert(err_);
			}
			
			me.gMarker.openInfoWindowHtml(me._getInfoWindowHtml());
		});
	}

	return this.gMarker;
}


PushPin.prototype.Hide = function()
{
	this.visible = false;
	if(this.gMarker != null)
	{
		this.gMarker.closeInfoWindow();
		this.gMarker.hide();
	}

	this._HideTableRow();

}

PushPin.prototype._HideTableRow = function()
{

	try
	{
		if(this.myTableRow != null)
		{
			var me=this;
			var itemTable = document.getElementById('idTableItems');

			var rIndex = this.myTableRow.rowIndex;
			if(rIndex >= 0)
			{
				itemTable.deleteRow(rIndex);
			}
			this.myTableRow = null;

			if(itemTable.rows == null || itemTable.rows == 'undefined' || itemTable.rows.length <= 0)
			{
				var parentTd = document.getElementById('idTdItemsCol');
				if(parentTd != null && parentTd != 'undefined')
				{
					parentTd.style.display='none';
				}
			}
		}
	}
	catch (err1)
	{
		alert(err2);
	}

}

PushPin.prototype._getInfoWindowHtml = function()
{
	var nYellowStars = Math.floor(this.rating);
	var nGrayStars = MaxRating - Math.ceil(this.rating);
	var nYellowGrayStars = MaxRating - nYellowStars - nGrayStars;

	var retHtml = "";
	var l_url = this.url;
	if(l_url == "")
	{
		l_url = 'node/' + this.nodeId;
	}
	retHtml += '<body style="padding:0;margin:0;>';
	retHtml += '<span style="font-size:10px"><b><a href="' + l_url + ' ">' + CapitalizeWords(trim(this.name)) + '</a></b><span><br />';
	retHtml += '<span style="font-size:10px">' + trim(this.street) + "</span> <br />";
	retHtml += '<span style="font-size:10px">' + trim(this.city) + ", " + trim(this.state) + " " + trim(this.zip) + ", " + trim(this.country) + "</span><br />";
	retHtml += '<span style="font-size:10px">' + trim(this.phNum) + "</span>";
	
	retHtml += '<p style="line-height:10pt;"/>';

	if(this.startTime != null && this.endTime != null && this.startTime.toString().indexOf('NaN')<0 && this.endTime.toString().indexOf('NaN')<0 && this.startTime.toString()!='Invalid Date' && this.endTime.toString()!='Invalid Date')
	{
		retHtml += '<span style="font-size:10px">' + '<b>Start:&nbsp;</b>' + ToLocalTimeString(this.startTime) + "</span> <br />";
		retHtml += '<span style="font-size:10px">' + '<b>End:&nbsp;&nbsp;</b>' + ToLocalTimeString(this.endTime) + "</span>";
		retHtml += '<p style="line-height:10pt;"/>';
	}
	
	imgSize = "12px";
	for(i=0; i<nYellowStars; i++)
	{
		retHtml += '<img src="' + moduleBasePath + '/YellowStar.png" height="' + imgSize + '" width="' + imgSize +'" alt="' + this.rating + '" />';
	}
	for(i=0; i<nYellowGrayStars; i++)
	{
		retHtml += '<img src="' + moduleBasePath + '/YellowGrayStar.png" height="' + imgSize + '" width="' + imgSize +'" alt="' + this.rating + '" />';
	}
	for(i=0; i<nGrayStars; i++)
	{
		retHtml += '<img src="' + moduleBasePath + '/GrayStar.png" height="' + imgSize + '" width="' + imgSize +'" alt="' + this.rating + '" />';
	}
	
        var l_rating = 0;
        if(this.rating != 0 && this.rating != '')
        {
             l_rating = this.rating;
        }
        retHtml += '<span style="font-size:10px"><a href="' + l_url + ' ">(Avg: ' + l_rating + ')</a>&nbsp;<a href="' + l_url + ' ">Comments</a></span>';

//        if(this.rating != 0)
//	{
//		retHtml += '<span style="font-size:10px">(Avg: ' + this.rating + ')&nbsp;<a href="' + l_url + ' ">Comments</a></span>';
//	}
//	else
//	{
//		retHtml += '<span style="font-size:10px"><a href="' + l_url + ' ">(Rate it!)</a>&nbsp;<a href="' + l_url + ' ">Comments</a></span>';
//	}

	l_distance = this.cachedDistance;
	if(l_distance != '')
	{
		retHtml += '<p style="line-height:0pt;"/>';
		//retHtml += '<div id="idDivDirections" style="padding:0;margin:0">';
		retHtml += '<span style="font-size:10px">' + l_distance + ' away </span>';
		retHtml += '&nbsp;|&nbsp;';
		retHtml += '<span style="font-size:10px"><a href="http://maps.google.com/maps?f=d&hl=en&saddr=' + this.cachedMyLocation + '&daddr=' + this.mapPoint.address + '" target="_blank">Directions</a></span>';
//		retHtml += '&nbsp;|&nbsp;';
//		retHtml += '<span style="font-size:10px">Google Maps</span>';
//		retHtml += '</div>';
	}

	retHtml += '<p style="line-height:0pt;"/><span style="font-size:10px; font-weight:bold">' + this.category + ';&nbsp;' + this.subcategory + '</span>';
	retHtml += "</body>"; 

	return retHtml;
}

PushPin.prototype.ComputeDistance = function(newLocationString)
{
	if(this.cachedMyLocation != newLocationString)
	{
		this.cachedMyLocation = newLocationString;
	}

	if(this.cachedMyLocation == '')
	{
		this.cachedDistance = '';
		return;
	}

	if(this.gDir == null)
	{
		this.gDir = new GDirections();
		var me = this;
		GEvent.addListener(this.gDir, "load", function()
		{
			//the variable this is set to the event source (in this case, gDir)
			status = this.getStatus();
			try
			{
				MaxRetries = 20;
				RetryCount = 0;
				while(RetryCount < MaxRetries)
				{
					RetryCount ++;

					if(this.getStatus().code == 200)
					{
						//alert('200 OK');
						break;
					}
					Sleep(10);
				}

				var distanceObj = this.getDistance();
				me.cachedDistance = distanceObj.html;	
			}
			catch (err)
			{
				//alert(err);
			}
		}); //end of load event handler

//		GEvent.addListener(this.gDir, "error", function()
//		{
//			if (me.gDir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
//			 alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + me.gDir.getStatus().code);
//		   else if (me.gDir.getStatus().code == G_GEO_SERVER_ERROR)
//			 alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + me.gDir.getStatus().code);
//		   
//		   else if (me.gDir.getStatus().code == G_GEO_MISSING_QUERY)
//			 alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + me.gDir.getStatus().code);
//
//		//   else if (gdir.getStatus().code == G_UNAVAILABLE_ADDRESS)  <--- Doc bug... this is either not defined, or Doc is wrong
//		//     alert("The geocode for the given address or the route for the given directions query cannot be returned due to legal or contractual reasons.\n Error code: " + gdir.getStatus().code);
//			 
//		   else if (me.gDir.getStatus().code == G_GEO_BAD_KEY)
//			 alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + me.gDir.getStatus().code);
//
//		   else if (me.gDir.getStatus().code == G_GEO_BAD_REQUEST)
//			 alert("A directions request could not be successfully parsed.\n Error code: " + me.gDir.getStatus().code);
//			
//		   else alert("An unknown error occurred.");
//		});

	}

	var query = 'from: ' + this.cachedMyLocation + ' to: ' + this.mapPoint.address;
	this.gDir.load(query);
}

//PushPin.prototype._getDistance = function()
//{
////	this.cachedMyLocation = '';
////	this.cachedDistance = '';
//
//	var newLocation = desimap_GetMyLocation();
//
//	if(newLocation == 'undefined' || newLocation == null)
//	{
//		this.cachedMyLocation = '';
//		this.cachedDistance = '';
//		return '';
//	}
//
//	if(newLocation != this.cachedMyLocation)
//	{
//		this.cachedMyLocation = newLocation;
//		this.cachedDistance = desimap_GetDistance(this.mapPoint.address, this.cachedMyLocation);
//	}
//
//	return this.cachedDistance;
//}

function SearchPin(givenPin)
{
	if(givenPin == null) return null;

	PushPinArray = desimap_GetOrCreatePushPinArray(givenPin.category, givenPin.subcategory);

	var arrLen = PushPinArray.length;
	for(i=0; i<arrLen; i++)
	{
		curPushPin = PushPinArray[i];
		if(curPushPin.mapPoint.lat == givenPin.mapPoint.lat &&
			curPushPin.mapPoint.lng == givenPin.mapPoint.lng &&
			trim(curPushPin.mapPoint.address.toLowerCase()) == trim(givenPin.mapPoint.address.toLowerCase()) &&
			trim(curPushPin.category.toLowerCase()) == trim(givenPin.category.toLowerCase()) &&
			trim(curPushPin.subcategory.toLowerCase()) == trim(givenPin.subcategory.toLowerCase())
			)
		{
			return curPushPin;
		}
	}//end of for
	return null;
}

/**
	MAP Location points
*/

function MapPoint(_lat, _lng, _address, _predefined, _myPushPin)
{
	this.myPushPin = _myPushPin;
	this.lat = _lat;
	this.lng = _lng;
	this.address = _address;
	this.predefined = _predefined;
	this.defaultZoom = 12;

	if(this.lat == -1000 || this.lng == -1000)
	{
		//mihir
		var geocoder = new GClientGeocoder;
		var me=this;
		
		geocoder.getLatLng(this.address, function(point)
		{
			if (point)
			{
				me.lat = point.lat();
				me.lng = point.lng();
				
				if(me.myPushPin.showPending)
				{
					me.myPushPin.Show();
				}

				var _ajaxCall = new AjaxCall(ajaxCallHandlerPath);
				_ajaxCall.SetCallback('');
				_ajaxCall.SendRequest("SetLatLng", 'NodeId=' + me.myPushPin.nodeId + '&Lat=' + me.lat + '&Lng=' + me.lng, false);
			}
		});
	}
}

MapPoint.prototype.myPushPin;
MapPoint.prototype.lat;
MapPoint.prototype.lng;
MapPoint.prototype.address;
MapPoint.prototype.predefined;
MapPoint.prototype.defaultZoom;


MapPoint.prototype.Zoom = function()
{
	this.Zoom1(this.defaultZoom);
}

MapPoint.prototype.Zoom1 = function(zoomLevel)
{
	if(gMap == null) return;
	gMap.setCenter(new GLatLng(this.lat, this.lng, false), zoomLevel);
}
