/**************************************************************************
Script:	jPart.BingList.js
Author:	SharejPoint.com
Purpose:  Plot sharepoint list field on a Bing map
Dependencies:
	jPointLoader.js has to be on the same page or form editor webpart
*************************************************************************/
//Add include extension
//Include CSS and JS
jP.include(['http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=6.2&mkt=en-us']);

myjPart.ShowConfigDefaults = [	
	["LookupSiteURL","Absolute path to lookup list site location","/"]
   ,["LookupListName","Lookup list name","LookupList"]
    ,["LookupMaxDisplay","Maximum List Items to Display","10"]
   ,["LookupViewName","View to use; blank to use default",""]
    ,["LookupCAML","Custom CAML (optional)",""]
    ,["MapWidth","Map Width","400"]
    ,["MapHeight","Map Height","200"]
    ,["MapZoomLevel","Map Zoom Level","3"]    
	];

myjPart.setjPartOptions({Plugin:{Name:'Bing List Map', Version:'2.0', Origin:'SharejPoint', Description:'Allows user with contributor rights to display contents of a SharePoint list on a Bing map', Developer:'Samir Sijercic'}});

var ZoomLEvel = 1;
var map = null;
var BingMapJpartProcessing = null;

$(document).ready(function() { //Wait page to load and then apply webpart logic
	if(myjParts[JpartProcessing] != null)
	{
		var thisWebpart = myjParts[JpartProcessing];
		
		BingMapJpartProcessing = JpartProcessing;
		
		try
		{
			//jPart user code goes here ---------------------------
			if(thisWebpart.Options.Local != null)
			{
				drawMap();
			}		
					
			//-----------------------------------------------------
		}catch(err){};
		JpartProcessing = JpartProcessing + 1;
	}
});

function drawMap()
{
	var thisWebpart = myjParts[BingMapJpartProcessing];
	var Options = thisWebpart.Options.Local;
	DataJSONObj= getjPointData(Options.LookupSiteURL, Options.LookupListName, 'Map Info View', Options.LookupCAML, Options.LookupMaxDisplay, null);
	var MapResults = new Array();
	$.each(DataJSONObj, function(idx, itemData)
	{
		var MapResult = {};
		//var sAddress = $(itemData).attr('ows_WorkAddress') + ',' + $(itemData).attr('ows_WorkCity') + ',' + $(itemData).attr('ows_WorkState') + ',' + $(itemData).attr('ows_WorkZip') + ',' + $(itemData).attr('ows_WorkCountry');	
		MapResult['Long'] = $(itemData).attr('ows_Longitude');
		MapResult['Lat'] = $(itemData).attr('ows_Latitude');
		//MapResult['Address'] = sAddress;
                //MapResult['Description'] = $(itemData).attr('ows_Title');
                //MapResult['CompanyDesc'] = $(itemData).attr('ows_Description');
                MapResult['Company'] = $(itemData).attr('ows_Title');
		MapResult['URL'] = $(itemData).attr('ows_WebPage');
		MapResult['CompanyLogo'] = $(itemData).attr('ows_CompanyLogo');
		MapResult['Itemid'] = $(itemData).attr('ows_ID');
		MapResult['Type'] = $(itemData).attr('ows_Partner_x0020_Type');
		
		MapResults.push(MapResult);
	});
	thisWebpart.MainDiv.append("<div id='myMap' style='position:relative; width:100%; height:350px;'></div>");
	//thisWebpart.MainDiv.append("<div id='myMap' style='position:relative; width:" + Options.MapWidth + "px; height:" + Options.MapHeight + "px;'></div>");
	ZoomLEvel = Options.MapZoomLevel;
	GetMap();
	


	$.each(MapResults, function(idx, itemData)
	{
		
		if(itemData.Long != undefined && itemData.Lat != undefined)
		{
			
			CreatePin(itemData.Long,itemData.Lat,itemData.Company,itemData.URL,itemData.CompanyLogo,itemData.Type,itemData.Itemid)
		}
		
		
		//Geocode(itemData.Address)
	});
}
function getjPointData(siteURL, listName, viewName, cAML, maxDisplay, viewFields)
{
	var Data = null;
	try
	{
		var thisSPObj = jP.Lists.getList(siteURL, listName);
		thisSPObj.ViewFields=viewFields;
		if(viewName != null && viewName.length > 0)
		{	
			thisSPObj.getSPView(viewName);}
		else
		{
			thisSPObj.getSPItemsWithQuery(cAML, maxDisplay);
		}	
		Data = thisSPObj.JQueryData;		
	}
	catch(err)
	{
	}
	return Data;
}
				
function GetMap()
{
	map = new VEMap('myMap');
	map.SetDashboardSize(VEDashboardSize.Tiny);
	map.HideScalebar();
	map.LoadMap();
}

function Geocode(address)
{
	//alert('Attempting to Geocode: ' + address);
	map.Find(null, address, null, null, 0, 10, false, false, false, true, ProcessResults)
}

function ProcessResults(layer, results, places, hasmore)
{
	if(places != null)CreatePin("Default", places[0]);
	//alert("Latitude: " + places[0].LatLong.Latitude + " Longitude= " + places[0].LatLong.Longitude);
}

function myCallback(itemurl)
{
        	var options = { url: itemurl, width: 800};

        	SP.UI.ModalDialog.showModalDialog(options);
}

function CreatePin(Long,Lat,Company,url,logo,type,itemid)
{

		

		if(url != undefined)
		{
			var arr1 = url.split(',');
			url = arr1[0];
		}
		else
		{
			url = '';
		}	
		if(logo != undefined)
		{
			var arr2 = logo.split(',');	
			logo = arr2[0];
		}		
		else
		{
			logo = '';
		}
		
		if(type == undefined)
		{
			type = '';	
		}
		else
		{
			type = type.replace(';#','</br>Partner Type:</br></br> ');
			type = type.replace(/;#/gi,'</br> ');
			
		}
		if(Company == undefined)
		{
			Company = '';
		}	
		
		
		
		var pin = new VEShape(VEShapeType.Pushpin, new VELatLong(Lat, Long));
		var viewitem = 'http://www.workengine.com/partners/Lists/Partners/DispForm.aspx?ID=' + itemid + '&ContentTypeId=0x010600F967F764C04F084B88E1F4073DF1EA18&IsDlg=1';
		

		//pin.SetTitle(Company);
		
		if(logo != '')
		{
			pin.SetDescription("<table width='100%'></td></tr><tr><td><img src='" + logo + "'/></td></tr></table><table width='100%'><tr><td><a href=javascript:myCallback('" + viewitem + "')>" + Company + "</a></table><table><tr><td><a href='" + url + "' target='_blank'>" + url + "</a></td></tr><tr><td>" + type + "</td</tr></table>");
		}		
		else
		{
			pin.SetDescription("<table width='100%'><tr><td><a href=javascript:myCallback('" + viewitem + "')>" + Company + "</a></table><table width='100%'><tr><td><a href='" + url + "' target='_blank'>" + url + "</a></td></tr><tr><td>" + type + "</td</tr></table>");
		}

		

		//pin.SetPhotoURL(logo);
		//pin.SetMoreInfoURL(url);
		//if(Company == 'LMR Solutions')
		//{
		//	pin.SetCustomIcon("<img src='http://www.epmlive.com/images/star.jpg' style='position:relative;left:0px;top:-12px'/>");
		//}
		//else
		//{
			pin.SetCustomIcon("<img src='http://www.epmlive.com/images/mappin.png' style='position:relative;left:0px;top:-12px'/>");
		//}
		map.AddShape(pin);
		map.SetZoomLevel(1);
		

			
}

		



//End Webpart logic code -----------------------------------
