// JavaScript Document
var map = null;
var layer;
var polyPoints = new Array();
var rectPoints = new Array();
var isDrawingPolygon = false;
var origCursor = null;
var index = 0;
var results = null;
var polyID=0;
var shapeLayer,pinLayer;
var circleLayer = null;
var circle = null;
var rectLayer = null;
var rectangle = null;
var selecting = false;
var EndLatLon = null;
var radiusLine;
var radius = 0;
var down = 0;
var searched = 0;
var earthRadius = 6371;
var X=0,Y=0;
var x1,x2,x3,x4,y1,y2,y3,y4;
var origin;
var pinArray = new Array();
var locationArray = new Array();
var f=0;
var rect_org_X;
var rect_org_Y;
var rect_fin_X;
var rect_fin_Y;
var cir_cen_X;
var cir_cen_Y;
var site_url = "http://www.optionmatrix.biz/cats/testing/front";
/***********************************************************************************/

function findPos(obj)
{
	var curleft = curtop = 0;

	if (obj.offsetParent)
	{
		curleft = obj.offsetLeft

		curtop = obj.offsetTop

		while (obj == obj.offsetParent)
		{
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return [curleft,curtop];
}

function getLatLong(e)
{
    //Get the pixel coordinates from the click event, convert to LatLong value
    var x = e.mapX;
    var y = e.mapY;
    pixel = new VEPixel(x, y);
    latLong = map.PixelToLatLong(pixel);
    map.SetCenterAndZoom(latLong, 5);
}

function defaultMapView()
{
    map.SetCenterAndZoom(new VELatLong(40.80706035607121, -94.65820312500001), 4);
}

function OnClick(e)
{
	// Are we drawing something?
	if (isDrawingPolygon)
	{
		// Retrieve the location where we clicked.
		var loc = map.PixelToLatLong(new VEPixel(e.mapX, e.mapY));
		
		if (e.leftMouseButton && !e.rightMouseButton)
		{
			// This is to prevent further click processing.
			return false;
		}
	}
	else
	{
		// Nothing to do here.
		return true;
	}
}
	
function SetCursor(isDrawing)
{
	document.getElementById('myMap').childNodes[0].style.cursor = isDrawing ? "crosshair" : origCursor;
}

var rect_left_X;
var rect_left_Y;
function AddRectangle()
{
	//alert('Left click and drag the mouse on the map to draw the rectangle of any size.');
	if(circle != null)
		map.DeleteShape(circle);
	if(rectangle != null)
		map.DeleteShape(rectangle);
	for(var i=0; i < pinLayer.GetShapeCount(); i++)
	{
		var shape = pinLayer.GetShapeByIndex(i);
		var latlong = shape.GetPoints()[0];
		var lat = latlong.Latitude;
		var lon = latlong.Longitude;
		shape.SetCustomIcon("<div class='transPin'></div>");
		//shape.SetDescription('');
	}
	map.AttachEvent("onmouseup",rectangleMouseUpHandler);
	map.AttachEvent("onmousedown",rectangleMouseDownHandler);
	map.AttachEvent("onmousemove",rectangleMouseMoveHandler);
	SetCursor(true);
}
////////////// deva2 rectangle ///////////////////
function rectangleSearch()
{
	var counter=0,k=1;
	var camp_name = '';
	//var camp_website = '';
	var is_there = new Array();
	var total = 0;
	var ids_in = document.getElementById('total_ids').value;
	var ids_len = document.getElementById('total_ids_len').value;// added new
//    alert(ids_in);
//	alert(ids_len);
	var camp_id = ids_in.split(',');
	var rect_ids = '';
	var test=0;
	//loop through shapes on the shape layer and see if they are within the polygon
	for(b=0;b<ids_len;b++)
	{
		for(var i=0; i <pinLayer.GetShapeCount(); i++)
		{
			var shape = pinLayer.GetShapeByIndex(i);
			var latlong = shape.GetPoints()[0];
			var lat = latlong.Latitude;
			var lon = latlong.Longitude;
			
			if(pointInRectangle(rectPoints,lat,lon))
			{
				camp_name = names1[i];				
				temp_id = camp_id[b];
				if(camp_name == temp_id)
				{
					is_there[test]=i;
                    //alert('is_there['+test+']: '+i);
					total += 1;
					rect_ids += camp_id[b] + ',';
					test++;
				}
			}
		}
	}
    //alert(total);
	if(total>0)
	{

		for(var i=0; i < total; i++)
		{
            //alert(is_there[i]);
			if(is_there[i]!=undefined || is_there[i]!=null)
			{
				var x = is_there[i];
                //alert(x);
				var shape1 = pinLayer.GetShapeByIndex(x);
				if(names[x]!=undefined || names[x]!=null)
				{
                    var desc = getInfoBox(names[x],camp_website[x],camp_links[x],imgs[x],comm_zips[x]);
                    shape1.SetTitle('');
                    shape1.SetCustomIcon("<div class='pinStyle'></div>");
					shape1.SetDescription(desc);
				}
                counter++;
			}			
		}
	}
	//alert(counter)
	//document.getElementById('total_comms').value=total;
	if(total!='')
	{
        //alert('Your selected region have '+counter+ ' camps');
	}
	//document.getElementById('total_ids').value=rect_ids;
	if(counter==0)
  	  alert("There are no cams in the selected region!");
	else
	{
//		var rect_mid_X=Math.abs(rect_org_X+Math.abs((rect_fin_X-rect_org_X)/2));
//		var rect_mid_Y=Math.abs(rect_org_Y+Math.abs((rect_fin_Y-rect_org_Y)/2));
//		end = map.PixelToLatLong(new VEPixel(rect_mid_X,rect_mid_Y));
//		map.SetCenter(new VELatLong(end.Latitude,end.Longitude));
		//map.SetZoomLevel(8);
	}
}
function rectangleMouseUpHandler(e)
{
	//alert('hi')
	rect_fin_X = e.mapX; 
	rect_fin_Y = e.mapY; 
	// On mouse up, if in selecting mode cancel selecting mode
	if(selecting)
	{ 
		// cancel selecting mode
		selecting = false;
		rect_isClick_flag=false;
		rectangleSearch();
		SetCursor(false);
		detachRectangleEvents();
	}
	end = map.PixelToLatLong(new VEPixel(rect_fin_X,rect_fin_Y));
}
function rectangleMouseDownHandler(e)
{
	// disable the VE mouse events 
	if (e.leftMouseButton)
	{
		// enable selecting mode
		selecting = true;
		// set the start points 
		X = e.mapX; 
		Y = e.mapY; 
		rect_left_X=Math.round(e.mapX);
		rect_left_Y=Math.round(e.mapY);
		origin = map.PixelToLatLong(new VEPixel(X,Y));
		
		rect_org_X = e.mapX; 
		rect_org_Y = e.mapY; 
		origin = map.PixelToLatLong(new VEPixel(rect_org_X,rect_org_Y));
		return true;
	}
    else
        return false;
}
function rectangleMouseMoveHandler(e)
{
	//When moving the mouse, if in "selecting" mode, draw, otherwise do nothing.
	if(!selecting) 
	{
		return false;
	} 
	else 
	{
		// clear select box
		if (rectangle) {map.DeleteShape(rectangle)};

		// set the latest endpoints (opposite side of the selection box) 
		X = e.mapX; 
		Y = e.mapY;
		EndLatLon = map.PixelToLatLong(new VEPixel(X, Y));
		// create new selection box (VEShape) from start and end (corners) coordinates
		rectPoints = [origin,new VELatLong(origin.Latitude, EndLatLon.Longitude),EndLatLon,new VELatLong(EndLatLon.Latitude, origin.Longitude)];
		rectangle = new VEShape( 
			VEShapeType.Polygon, 
			[
			origin,
			new VELatLong(origin.Latitude, EndLatLon.Longitude),
			EndLatLon,
			new VELatLong(EndLatLon.Latitude, origin.Longitude)
			]);
		rectangle.HideIcon();
		map.AddShape(rectangle); 
		return true;
	}
}

function pointInRectangle(points,lat,lon)
{
	var i;
	var j=points.length-1;
	var inRect=false;
	
	for (i=0; i<points.length; i++)
	{
		if (points[i].Longitude<lon && points[j].Longitude>=lon ||  points[j].Longitude<lon && points[i].Longitude>=lon)
		{
			if (points[i].Latitude+(lon-points[i].Longitude)/(points[j].Longitude-points[i].Longitude)*(points[j].Latitude-points[i].Latitude)<lat)
			{
				inRect=!inRect;
			}
		}
		j=i;
	}
	
	return inRect;
}
function detachRectangleEvents()
{
	// Detach all events
	map.DetachEvent("onmouseup",rectangleMouseUpHandler);
	map.DetachEvent("onmousedown",rectangleMouseDownHandler);
	map.DetachEvent("onmousemove",rectangleMouseMoveHandler);
}

/**************		Functions related to drawing circle on the map		****************************/
function StartDrawCircle()
{
	//alert('Left click and drag the mouse on the map to draw the circle of any radius.');
	
	if(circle != null)
		map.DeleteShape(circle);
	if(rectangle != null)
		map.DeleteShape(rectangle);
	for(var i=0; i < pinLayer.GetShapeCount(); i++)
	{
		var shape = pinLayer.GetShapeByIndex(i);
		shape.SetCustomIcon("<div class='transPin'></div>");
		shape.SetDescription('');
	}
	SetCursor(true);
	map.AttachEvent("onmouseup",CircleMouseUpHandler);
	map.AttachEvent("onmousedown",CircleMouseDownHandler);
	map.AttachEvent("onmousemove",CircleMouseMoveHandler);
}

///// deva3  radious ///////////////
function radiusSearch()
{
	var numShapes = pinLayer.GetShapeCount();
	var counter=0,k=1;
	var camp_name = '';
	var is_there = new Array();
	var total = 0;
	var ids_in = document.getElementById('total_ids').value;
	var ids_len = document.getElementById('total_ids_len').value;// added new
	var camp_id = ids_in.split(',');
	var rect_ids = '';
	var test=0;
	for(b=0;b<ids_len;b++)
	{
		for(var i=0; i < numShapes; i++)
		{
			var shp = pinLayer.GetShapeByIndex(i);
			var latlong2 = shp.GetPoints()[0];
			var d = distance(origin,latlong2);
			
			if(Math.abs(d)<= Math.abs(radius))
			{
				camp_name = names1[i];
				
				temp_id = camp_id[b];
				
				if(camp_name == temp_id)
				{
					is_there[test]=i;
					total += 1;
					rect_ids += camp_id[b] + ',';
					test++;
				}
			}
		}
	}
	
	if(total>0)
	{
		for(var i=0; i < total; i++)
		{
			if(is_there[i]!=undefined || is_there[i]!=null)
			{
				var x = is_there[i];
				var shape = pinLayer.GetShapeByIndex(x);
                
				if(names[x]!=undefined || names[x]!=null)
				{
                    var desc = getInfoBox(names[x],camp_website[x],camp_links[x],imgs[x],comm_zips[x]);
                    shape.SetTitle('');
                    shape.SetCustomIcon("<div class='pinStyle'></div>");
					shape.SetDescription(desc);
                }
                counter++;
			}			
		}
	}
	//document.getElementById('total_comms').value=total;
	if(total!='')
	{
        //alert('Your selected region have '+counter+ ' camps');
	}
	//document.getElementById('total_ids').value = rect_ids;
	if(counter==0)
  	  alert("There are no camps in the selected region!");
	else
	{
		//circle_latLon = map.PixelToLatLong(new VEPixel(cir_cen_X,cir_cen_Y));
		//map.SetCenter(new VELatLong(circle_latLon.Latitude,circle_latLon.Longitude));
		//map.SetZoomLevel(8);
	}
}
function distance(latlong,latlong2)
{
	var lat1 = latlong.Latitude;
	var lon1 = latlong.Longitude;
	var lat2 = latlong2.Latitude;
	var lon2 = latlong2.Longitude;
	var factor = Math.PI/180;
	var dLat = (lat2-lat1)*factor;
	var dLon = (lon2-lon1)*factor;
	var a = Math.sin(dLat/2) * Math.sin(dLat/2)+Math.cos(lat1*factor)*Math.cos(lat2*factor)*Math.sin(dLon/2) * Math.sin(dLon/2);
	var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
	var d = earthRadius * c;
	return d;
}
		
	//draw line between two points
function drawLine(latlong,latlong2,idnum)
{
	var poly = new VEShape(VEShapeType.Polyline,[latlong,latlong2]);
	var icon = "<div style='font-size:12px;font-weight:bold;border:solid 2px Black;background-color:White;width:10px;'>"+idnum+"</div>";
	poly.SetCustomIcon(icon);
	map.AddShape(poly);
}
function CircleMouseUpHandler(e)
{
	down=0;
	if (e.leftMouseButton)
	{
		var x = e.mapX;
		var y = e.mapY;
		var latlong = map.PixelToLatLong(new VEPixel(x, y));
		map.DeleteShape(radiusLine);
		radiusSearch(latlong);
		X=0;
		Y=0;
		SetCursor(false);
		detachCircleEvents();
	}
}
function CircleMouseDownHandler(e)
{
	if (e.leftMouseButton)
	{
		X = e.mapX;
		Y = e.mapY;
		origin = map.PixelToLatLong(new VEPixel(X,Y));
		down=1;
		radius = 0;
		if(searched==1)
		{
			map.DeleteShape(circle);
			circleLayer.DeleteAllShapes();
		}
		return true;
	}
}
	
function CircleMouseMoveHandler(e)
{
	if (down==1)
	{
		var x = e.mapX;
		var y = e.mapY;
		var dx = Math.abs(X)-Math.abs(x);
		var dy = Math.abs(Y)-Math.abs(y);
		if(Math.abs(dx) > 5 || Math.abs(dy) > 5)
		{
			var latlong = map.PixelToLatLong(new VEPixel(x, y));
			radius = distance(origin,latlong);
			if(searched==1)
			{
				map.DeleteShape(circle);
				map.DeleteShape(radiusLine);
			}
			else
				searched=1;
			drawCircle(radius,e);
			drawRadius(latlong);
		}
	}
}

function drawCircle(radius,e)
{
	var lat = (origin.Latitude * Math.PI) / 180; //rad
	var lon = (origin.Longitude * Math.PI) / 180; //rad
	var d = parseFloat(radius)/earthRadius;  // d = angular distance covered on earth's surface
	var locs = new Array();
	for (x = 0; x <= 360; x++)
	{
		var p2 = new VELatLong(0,0);
		brng = x * Math.PI / 180; //rad
		p2.Latitude = Math.asin(Math.sin(lat)*Math.cos(d) + Math.cos(lat)*Math.sin(d)*Math.cos(brng));
		p2.Longitude = ((lon + Math.atan2(Math.sin(brng)*Math.sin(d)*Math.cos(lat), Math.cos(d)-Math.sin(lat)*Math.sin(p2.Latitude))) * 180) / Math.PI;
		p2.Latitude = (p2.Latitude * 180) / Math.PI;
		locs.push(p2);
	}
	circle = new VEShape(VEShapeType.Polyline, locs);
	circle.HideIcon();
	map.AddShape(circle);
}

function drawRadius(latlong)
{
	radiusLine = new VEShape(VEShapeType.Polyline, [origin,latlong]);
	radiusLine.HideIcon();
	map.AddShape(radiusLine);
}

function detachCircleEvents()
{
	// Detach all events
	map.DetachEvent("onmouseup",CircleMouseUpHandler);
	map.DetachEvent("onmousedown",CircleMouseDownHandler);
	map.DetachEvent("onmousemove",CircleMouseMoveHandler);
}

/*****************		Circle fuctions end here		***********************************************/
function clearSelection()
{
	if(circle != null)
		map.DeleteShape(circle);
	if(rectangle != null)
		map.DeleteShape(rectangle);
	for(var i=0; i < pinLayer.GetShapeCount(); i++)
	{
		var shape = pinLayer.GetShapeByIndex(i);
		var latlong = shape.GetPoints()[0];
		var lat = latlong.Latitude;
		var lon = latlong.Longitude;
		shape.SetCustomIcon("<div class='transPin'></div>");
	}
    detachCircleEvents();
    detachRectangleEvents();
    //map.SetCenterAndZoom(new VELatLong(40.80706035607121, -94.65820312500001),4);
}

function getInfoBox(name,camp_website,camp_link,img,comm_zip)
{
    var camp_url = site_url+'/camp-profile/'+camp_link+'.html';    

    if(img=='' || img==null)
    {
        photoURL = "http://www.optionmatrix.biz/cats/testing/images/noimage.gif";
    }
    else
    {
        photoURL = "http://www.optionmatrix.biz/cats/testing/images/"+img;
    }

    if(comm_zip=='' || comm_zip==undefined)
    {
        cmzip = '---';
    }
    else
    {
        cmzip = comm_zip;
    }
    if(name=='' || name==undefined)
    {
        namesa = '---';
    }
    else
    {
        namesa = name;
    }
    var infobox = "<div align='left' style='width:210px;'>";
    infobox += "<table width='100%' border='0' cellpadding='0'>";
    infobox += "<tr>";
    infobox += "<td align='left' valign='top'><a href='"+camp_url+"' alt='"+namesa+"' title='"+namesa+"' target='_blank'><img src='"+photoURL+"' width='100px' height='100px' border='0'></a></td>";
    infobox += "</tr>";
    infobox += "<tr>";
    infobox += "<td align='left' valign='top' height='2px'></td>";
    infobox += "</tr><tr>";
    infobox += "<td align='left' valign='top' height='2px' class='label'><a href='"+camp_url+"' alt='"+namesa+"' title='"+namesa+"' target='_blank'>"+namesa+"</a></td>";
    infobox += "</tr><tr>";
    infobox += "<td align='left' valign='top' height='2px'></td>";
    infobox += "</tr><tr>";
    infobox += "<td align='left' valign='top'>";
    infobox += "<table width='100%' border='0' cellpadding='0'>";
    infobox += "<tr>";
    infobox += "<td align='left' valign='top' width='40%'>";
    infobox += "<table width='100%' border='0'>";
    infobox += "<tr>";
    infobox += "<td align='left' valign='top' class='label1' style='width:44%'><strong>Website: </strong></td>";
    infobox += "<td align='left' valign='top' class='label1' style='width:56%'>"+camp_website+"</td>";
    infobox += "</tr>";
    infobox += "<tr>";
    infobox += "<td align='left' valign='top' class='label1'><strong>Zip:</strong></td>";
    infobox += "<td align='left' valign='top' class='label1'>"+cmzip+"</td>";
    infobox += "</tr></table></td></tr>";
    infobox += "</table></td></tr>";
    infobox += "<tr><td>&nbsp;</td></tr></table></div>";

    return infobox;
}

// SLIDER *******************
function Map_SetZoom(num){map.SetZoomLevel(num);}

function Map_Pan(dir){var pixelsToPan = 150; switch(dir){case 'R': 

map.Pan(pixelsToPan, 0);return;case 'D': map.Pan(0, 

pixelsToPan);return;case 'U': map.Pan(0, -pixelsToPan);return;case 'L': 

map.Pan(-pixelsToPan, 0);return;case 'UL': map.Pan(-pixelsToPan, 

-pixelsToPan);return;case 'DL': map.Pan(-pixelsToPan, 

pixelsToPan);return;case 'DR': map.Pan(pixelsToPan, 

pixelsToPan);return;case 'UR': map.Pan(pixelsToPan, 

-pixelsToPan);return;}}


function Map_SetBirdLabels(labels){if(labels) 

Map_SetStyle(VEMapStyle.BirdseyeHybrid);else 

Map_SetStyle(VEMapStyle.Birdseye);}


function Map_SetStyle(type){map.SetMapStyle(type);}



